今天在搗鼓rmi時候,出現一個問題,客戶端一直顯示一個莫名其妙的ip地址拒絕訪問,這就很奇怪了,哪里來的?后來經過排查發現這個ip地址是虛擬機的一個虛擬網卡的ip地址,不知道為什么客戶端在尋找服務器的ip地址的時候會自動映射到該虛擬機的ip上。解決的方法是先將這個虛擬網卡關了,然后重啟rmi的服務器端就可以正確連接了。(ps:重啟后在打開虛擬網卡,就相互不影響了)。
個人猜測的是,在服務器注冊服務時候,會自動選擇一個ip地址,這個ip地址在選擇時候出現了錯誤。也沒找到java這塊的源碼。下面上源碼,有大哥可以幫幫小弟解答嗎。。。
服務器:
import java.rmi.Naming; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; public class RegistryService { public static void main(String[] args) { try { Registry registry= LocateRegistry.createRegistry(8848); HellowRegistryFacade hello=new HellowRegistryFacadeImpl(); registry.rebind("HellowRgistry",hello); System.out.println("==啟動RMI服務成功!"); } catch (RemoteException e) { e.printStackTrace(); } } }
客戶端:
import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; public class RegistryClient { public static void main(String[] args) { Registry registry=null; try { registry=LocateRegistry.getRegistry("192.168.1.3",8848); HellowRegistryFacade hello=(HellowRegistryFacade) registry.lookup("HellowRgistry"); String response=hello.helloWorld("朋友"); System.out.println(response); } catch (RemoteException e) { e.printStackTrace(); } catch (NotBoundException e) { e.printStackTrace(); } } }
接口
import java.rmi.Remote; import java.rmi.RemoteException; public interface HellowRegistryFacade extends Remote { String helloWorld(String name) throws RemoteException; }
接口實現
import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; public class HellowRegistryFacadeImpl extends UnicastRemoteObject implements HellowRegistryFacade { private static final long serialVersionUID=1L; protected HellowRegistryFacadeImpl() throws RemoteException { } @Override public String helloWorld(String name) throws RemoteException { return "[Registry] 你好!"+name; } }
問題解決了,java虛擬機在設置ip地址時,會在本地的host文件中讀取,而不是從顯卡獲取,因此導致了錯誤出現。解決方法時用System.setProperty("
java.rmi.server.hostname",正確ip);即可
");