RMI简单例子

1)定义一个接口
public interface HelloInterface extends Remote{
public String sayHello(String name) throws RemoteException;
}

2)实现接口
public class HelloInterfaceImpl extends UnicastRemoteObject implements HelloInterface{
protected HelloInterfaceImpl() throws RemoteException {
}
public String sayHello(String name) throws RemoteException {
String strHello = "你 " + name+" 欢器";
System.out.println(name +" 正 ");
return strHello;
}}


3)启动 server
HelloInterface hInterface = new HelloInterfaceImpl();
int port = 6666
LocateRegistry.createRegistry(port);
String address = "rmi://localhost:" + port + "/hello";
System.out.println("服务端地址: "+address);
Naming.bind(address,hInterface);
System.out.println(">>>服务端成功启动");


4)启动client
int port = 6666;
String address = "rmi://127.0.0.1:" + port + "/hello";
try {
HelloInterface hInterface = (HelloInterface) Naming.lookup(address);
System.out.println("客户端成功启动");
System.out.println(hInterface.sayHello("aaaa"));
} catch (MalformedURLException e) {

你可能感兴趣的:(rmi)