今天在捣鼓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);即可
");