Java rmi远程方法调用基本用法解析
本文主要介绍Java中的rmi的基本使用
1:项目架构
rmiserver的代码
public class RMIInterfaceImpl extends UnicastRemoteObject implements RMIInterface {
public RMIInterfaceImpl() throws RemoteException {
}
@Override
public Object sayHello(String name) throws RemoteException {
return "你好,你连接成功,姓名:"+name;
}
}
public class RMIServer {
public static void main(String[] args) {
try {
RMIInterface rmi = new RMIInterfaceImpl();
//注册通讯端口
LocateRegistry.createRegistry(RMIInterface.PORT);
//注册通讯路径
Naming.bind(RMIInterface.RMI_URL,rmi);
System.out.println("rmi服务端启动成功");
}catch (Exception e){
e.printStackTrace();
}
}
}
rmiconsumer
public class RMIConsumer {
public static void main(String[] args) {
//远程调用RMI
RMIInterface rmiInterface =null;
try{
rmiInterface =(RMIInterface) Naming.lookup(RMIInterface.RMI_URL);
Object ret = rmiInterface.sayHello("张先生");
System.out.println("测试远程调用成功,返回结果:"+ret);
}catch (Exception e){
e.printStackTrace();
}
}
}
4:总结
接口必须继承 Remote
接口的实现类必须继承 UnicastRemoteObject
Java rmi远程方法调用基本用法解析相关教程