定义
- RMI, 全称是remote method invocation, 远程方法调用,一种用于远程过程调用的应用程序编程接口,是纯 java 的网络分布式应用系统的核心解决方案之一。
- RMI目前使用Java远程消息交换协议 JRMP(Java Remote Messageing Protocol)进行通信,由于 JRMP 是专为 Java对象制定的,是分布式应用系统的百分之百纯 java 解决方案,用 Java RMI 开发的应用系统可以部署在任何支持 JRE的平台上
- 缺点是,由于 JRMP 是专门为 java 对象指定的,因此 RMI 对于非 JAVA 语言开发的应用系统的支持不足,不能与非 JAVA 语言书写的对象进行通信
基本原理

- 远程对象必须实现 UnicastRemoteObject,这样才能保证客户端访问获得远程对象时,该远程对象会把自身的一个拷贝以 Socket 形式传输给客户端,客户端获得的拷贝称为“stub” , 而 服 务 器 端 本 身 已 经 存 在 的 远 程 对 象 成 为“skeleton”,此时客户端的 stub 是客户端的一个代理,用于与服务器端进行通信,而 skeleton 是服务端的一个代理,用于接收客户端的请求之后调用远程方法来响应客户端的请求
服务端
import java.rmi.Remote;
import java.rmi.RemoteException;
// 定义远程服务的接口
public interface IHelloService extends Remote {
String sayHello(String msg) throws RemoteException;
}
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
// 定义远程服务的实现
public class IHelloServiceImpl extends UnicastRemoteObject implements IHelloService {
protected IHelloServiceImpl() throws RemoteException {
}
@Override
public String sayHello(String msg) throws RemoteException {
return "hello, "+ msg;
}
}
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
// 定义server端的实现
public class RmiServer {
public static void main(String[] args) throws RemoteException, MalformedURLException {
IHelloService helloService = new IHelloServiceImpl();
LocateRegistry.createRegistry(1099);
Naming.rebind("rmi://127.0.0.1/Hello", helloService);
System.out.println("rmi服务端, 启动成功");
}
}
客户端
import java.rmi.Remote;
import java.rmi.RemoteException;
// 引入远程服务
public interface IHelloService extends Remote {
String sayHello(String msg) throws RemoteException;
}
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
// 实现客户端
public class RmiClient {
public static void main(String[] args) throws RemoteException, NotBoundException, MalformedURLException {
IHelloService helloService = (IHelloService) Naming.lookup("rmi://127.0.0.1/Hello");
System.out.println(helloService.sayHello("lm"));
}
}
结果


976

被折叠的 条评论
为什么被折叠?



