RMI全称是Remote Method Invocation(远程方法调用),Java RMI威力体如今它强大的开发分布式网络应用的能力上,是纯Java的网络分布式应用系统的核心解决方案之一。其实它能够被看做是RPC的Java版本。可是传统RPC并不能很好地应用于分布式对象系统。而Java RMI 则支持存储于不一样地址空间的程序级对象之间彼此进行通讯,实现远程对象之间的无缝远程调用。html
//服务端接口 import java.rmi.Remote; public interface URLDispatcher extends Remote { String get()throws java.rmi.RemoteException; void add(String webAddress)throws java.rmi.RemoteException;; } //服务端接口实现 import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.server.UnicastRemoteObject; public class URLManagement extends UnicastRemoteObject implements URLDispatcher { protected URLManagement() throws RemoteException { super(); } public URLManagement(int port) throws RemoteException { super(port); } @Override public String get() throws RemoteException { System.out.println("www.baidu.com"); return "www.baidu.com"; } @Override public void add(String webAddress) throws RemoteException {} public static void main(String[] args) { try { //建立服务端 URLDispatcher hello = new URLManagement(1098); //注册1098号端口,注意这一步注册能够注册到别的机器上。 LocateRegistry.createRegistry(1098); //绑定服务端到指定的地址,这里的localhost对应的上一步注册端口号的机器 java.rmi.Naming.rebind("rmi://localhost:1098/URLDispatcher", hello); System.out.println("Ready"); } catch (Exception e) { e.printStackTrace(); } } } //客户端 import java.rmi.Naming; public class Main { public static void main(String[] args){ try { //客户端查找指定的服务 URLDispatcher hello = (URLDispatcher) Naming.lookup("rmi://localhost:1099/URLDispatcher"); //打印的结果应该是www.baidu.com System.out.println(hello.get()); } catch (Exception e) { e.printStackTrace(); } } }
注意:服务端启动后不会自动关闭,会一直等待客户端链接。java
http://blog.163.com/eye_ziye/blog/static/21447105120131127105623452/web
http://www.blogjava.net/zhenyu33154/articles/320245.html网络
http://www.ibm.com/developerworks/cn/java/j-rmiframe/分布式
http://blog.csdn.net/shirdrn/article/details/6359254ide
更多文章:http://blog.gavinzh.comspa