0%

RMI DEMO

RMI

一个简单的RMI demo。

服务端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package rmiserver;

import java.io.Serial;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;

import rmiinterface.RMIInterface;

public class ServerOperation extends UnicastRemoteObject implements RMIInterface {

@Serial
private static final long serialVersionUID = 1L;

private static final String CALL_HISTORY = """
通话记录详单:

电话号码:18662377270
起止时间:2021年4月6日21:56:16 到 2021年4月6日21:56:25

电话号码:17262894289
起止时间:2021年4月6日21:56:44 到 2021年4月6日21:56:46

电话号码:12345678909
起止时间:2021年4月6日21:56:59 到 2021年4月6日21:57:01

""";

protected ServerOperation() throws RemoteException {
super();
}

@Override
public String getCallHistory() throws RemoteException {
return CALL_HISTORY;
}

public static void main(String[] args) {
try { //special exception handler for registry creation
// 这里也可以手动在终端输入:start rmiregistry
LocateRegistry.createRegistry(1099);
System.out.println("java RMI registry created.");
} catch (RemoteException e) {
//do nothing, error means registry already exists
System.out.println("java RMI registry already exists.");
}

try {
Naming.rebind("//localhost/MyServer", new ServerOperation());
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}

对象接口

1
2
3
4
5
6
7
8
package rmiinterface;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface RMIInterface extends Remote {
String getCallHistory() throws RemoteException;
}

客户端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package rmiclient;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;

import javax.swing.JOptionPane;

import rmiinterface.RMIInterface;

public class ClientOperation {
public static void main(String[] args) throws MalformedURLException, RemoteException, NotBoundException {
RMIInterface look_up = (RMIInterface) Naming.lookup("//localhost/MyServer");
String response = look_up.getCallHistory();
JOptionPane.showMessageDialog(null, response);
}
}

运行方法

先运行服务端的main函数,再运行客户端的main函数。

运行结果