- 服务端
接口
package org.zln.net; import java.rmi.Remote; import java.rmi.RemoteException; /** * Created by sherry on 16/9/28. */ //1 必须继承Remote public interface IRmiServer extends Remote{ //2 必须抛出RemoteException异常 public String sayHello(String name) throws RemoteException; }
实现
package org.zln.net; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; /** * Created by sherry on 16/9/28. */ public class RmiServerImpl extends UnicastRemoteObject implements IRmiServer { @Override public String sayHello(String name) throws RemoteException { return "Hello "+name; } /** * 因为UnicastRemoteObject的构造方法抛出了RemoteException异常,因此这里默认的构造方法必须写,必须声明抛出RemoteException异常 * @throws RemoteException */ public RmiServerImpl() throws RemoteException { } }
注册
package org.zln.net; import java.net.MalformedURLException; import java.rmi.AlreadyBoundException; import java.rmi.Naming; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; /** * Created by sherry on 16/9/28. */ public class RmiServerMain { public static void main(String[] args) throws RemoteException, AlreadyBoundException, MalformedURLException { //创建一个远程对象 IRmiServer iRmiServer = new RmiServerImpl(); LocateRegistry.createRegistry(8888); Naming.bind("rmi://127.0.0.1:8888/IRmiServer",iRmiServer); System.out.println("远程对象绑定成功"); } }
这样,就把一个地址和一个远程对象进行了绑定
- 客户端
package org.zln.net; import java.net.MalformedURLException; import java.rmi.Naming; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.util.Date; /** * Created by sherry on 16/9/28. */ public class RmiClientMain { public static void main(String[] args) throws RemoteException, NotBoundException, MalformedURLException { IRmiServer iRmiServer = (IRmiServer) Naming.lookup("rmi://127.0.0.1:8888/IRmiServer"); long s = new Date().getTime(); for (int i = 0; i < 1000; i++) { System.out.println(iRmiServer.sayHello("张柳宁")); } long e = new Date().getTime(); System.out.println("耗时:"+(e-s)+"毫秒"); } }
从一段地址上获取到远程对象,然后就可以像是本地创建出来的对象那样进行访问了