1、Rmi服务端
1.1 写一个接口继承Remote接口
public interface ISayHello extends Remote {
public void sayHello() throws RemoteException;
public String sayHello(String msg) throws RemoteException;
}
1.2 写该接口的实现,该实现类要继承UnicastRemoteObject 类,然后加上该类构造方法
public class SayHelloImpl extends UnicastRemoteObject implements ISayHello {
private SayHelloImpl() throws RemoteException {
}
private static class Inner{
private static SayHelloImpl INSTANCE;
private static SayHelloImpl getInstance() throws RemoteException{
if(INSTANCE==null){
INSTANCE = new SayHelloImpl();
}
return INSTANCE;
}
}
public static SayHelloImpl getInstance() throws RemoteException{
return Inner.getInstance();
}
@Override
public void sayHello() throws RemoteException {
System.out.println("excute sayHello()-> hello world");
}
@Override
public String sayHello(String msg) throws RemoteException {
System.out.println("excute sayHello(String msg)-> hello "+ msg);
return "hello "+msg;
}
}
1.3 注册服务
public class MyRmiServer {
public static void main(String[] args) {
try {
ISayHello sayHello = SayHelloImpl.getInstance();
LocateRegistry.createRegistry(9993);
Naming.bind("rmi://localhost:9993/sayHello",sayHello);
System.out.println("MyRmiServer start success ....");
} catch (RemoteException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (AlreadyBoundException e) {
e.printStackTrace();
}
}
}
2 Rmi客户端
public class MyRmiClient {
public static void main(String[] args) {
try {
ISayHello sayHello = (ISayHello)Naming.lookup("rmi://localhost:9993/sayHello");
sayHello.sayHello();
String msg = sayHello.sayHello("MyRmiClient");
System.out.println("msg = " + msg);
} catch (NotBoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}