关于RMI 实现步骤

xiaoxiao2021-02-28  83

1. 抽象出一个接口, 扩展Remote 接口(直接实现会有问题)

public interface ServerHelloI extends Remote{ public String sayHello()throws RemoteException ; }

2. 实现抽象的接口,继承UnicastRemoteObject(这是用于帮助打包对象)

public class ServerHello extends UnicastRemoteObject implements ServerHelloI {     /** */ private static final long serialVersionUID = 1L; public ServerHello() throws RemoteException {         super();     } @Override public String sayHello() throws RemoteException{ return "hello world"; }           }

3. 实现类的属性都需要序列化

4. 启动服务端

public class Server { public static void main(String args[])       {           try{ //简单地返回一个合适的注册表存根,该存根发送调用到本地端口为1099的服务器表,那时           LocateRegistry.createRegistry(1099);           Naming.bind("rmi://127.0.0.1:1099/sayhello",new ServerHello());                System.out.println("Print server is ready.");           }catch(Exception e){               e.printStackTrace();           }       }   }

5. 客户端调用

public class Client { public static void main(String args[]) { try{// 无需设置如下代码,否则报错   //             System.setSecurityManager(new RMISecurityManager());   ServerHelloI server=(ServerHelloI) Naming.lookup("rmi://127.0.0.1:1099/sayhello");                System.out.println(server.sayHello());           }        catch(Exception e){                e.printStackTrace();          }   } }

如果报拒接访问,或者类型转化问题,再或者安全问题,请认真检查步骤和代码

转载请注明原文地址: https://www.6miu.com/read-74294.html

最新回复(0)