服务端:
定义远程接口:
package com.my.rmi; import java.rmi.Remote; import java.rmi.RemoteException; public interface Impl extends Remote{ public String name() throws RemoteException; }
实现接口:
package com.my.rmi; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; public class RmtImpl extends UnicastRemoteObject implements Impl{ private int i; public RmtImpl(int i) throws RemoteException { super(); this.i = i; } public RmtImpl() throws RemoteException{ } public String name() throws RemoteException{ return "test"+20*i; } }
注册远程对象:
package com.my.rmi; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; public class rmi { public static void main(String[] args) { Registry r = null ; try { RmtImpl s = new RmtImpl(25); r = LocateRegistry.createRegistry(50000); //也可以用它注册远程服务 //Naming.rebind("rmi://192.168.6.66:50000/mytest", s); r.rebind("mytest", s); } catch (Exception e1) { e1.printStackTrace(); } } }
客户端:
package com.my.rmi; import java.rmi.Naming; public class ClientRMI { public static void main(String[] args) { try { Impl oo = (Impl)Naming.lookup("rmi://192.168.6.66:50000/mytest"); System.out.println(oo.name()); } catch (Exception e) { e.printStackTrace(); } } }