让在某个 Java 虚拟机上的对象调用另一个 Java 虚拟机中的对象上的方法。
示例:
定义一个接口:
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface RMIInterface extends Remote {
public String test() throws RemoteException;
}
定义一个实现类:
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class RMIImpl extends UnicastRemoteObject implements RMIInterface {
public RMIImpl() throws RemoteException {
}
public String test() throws RemoteException {
return "Test";
}
}
服务端启动服务:
import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;
public class RMIServer {
public static void main(String args[]) throws Exception {
try {
RMIInterface rml = new RMIImpl();
// 本地主机上的远程对象注册表Registry的实例,并指定端口为 9999
LocateRegistry.createRegistry(9999);
//把远程对象注册到RMI注册服务器上,并命名为 rml
Naming.bind("rmi://localhost:9999/rml", rml);
} catch (Exception e) {
}
}
}
客户端使用服务:
import java.rmi.Naming;
public class RMIClient {
public static void main(String args[]) {
try {
RMIInterface rmi = (RMIInterface) Naming.lookup("rmi://localhost:9999/rml");
System.out.println(rmi.test());
} catch (Exception e) {
}
}
}
网友评论