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