首先在server端需要一个接口,继承自java.rmi.Remote
public interface Hello extends Remote {
public String say() throws RemoteException;
}
其次实现这个接口并继承java.rmi.server.UnicastRemoteObject
public class SayHello extends UnicastRemoteObject implements Hello{
protected SayHello() throws RemoteException{
super();
}
public String say() throws RemoteException {
return "Hello";
}
}
接着注册服务,绑定端口
public class Reg {
public static void main(String[] args) throws RemoteException,MalformedURLException{
LocateRegistry.createRegistry(1099);
SayHello sh = new SayHello();
Naming.rebind("rmi://localhost:1099/sh", sh);
System.out.println("注册完毕");
}
}
然后在客户端
public class Client {
public static void main(String[] args) throws RemoteException,MalformedURLException,NotBoundException{
Hello h = (Hello)Naming.lookup("rmi://localhost:1099/sh");
System.out.println(h.say());
}
}
即可
看看这个吧