我正在使用 RMI 为所有网络通信开发 Java 游戏。RMI 允许我在我的服务器上调用方法,但这对我来说还不够。我还希望服务器能够在连接的客户端之间传播消息。
我的客户查找服务器(它的接口扩展了 Remote)并在其上注册。它允许服务器知道谁连接了。我的客户还实现了一个扩展 Remote 的接口。这是我的代码的一部分:
接口声明:
public interface IServer extends Remote {
void connect(IClient Client) throws RemoteException, ExistingItemException;
//...
}
public interface IClient extends Remote {
public void notify(Notification Notification) throws RemoteException;
//...
}
服务器端:
//int RMIPort = 1099, ServerPort = 1100;
IServer Server = new RMIServer();
IServer Proxy = (IServer) UnicastRemoteObject.exportObject(Server, ServerPort);
LocateRegistry.createRegistry(RMIPort).rebind("//" + LocalIP + ":" +
RMIPort + "/xxx", Proxy);
客户端:
//Sets the local reference to IServer and creates the IClient
setInstance(new Client(Login, (IServer) LocateRegistry.getRegistry(RemoteIP).
lookup("//" + RemoteIP + ":" + RMIPort + "/xxx")));
//Gets the IClient and makes it available for the IServer to call notify(...)
Proxy.connect((IClient) (UnicastRemoteObject.exportObject(getInstance(), 0)));
该解决方案在本地有效,但在我尝试通过 Internet 使用时无效。
我已经设置了我的路由器以将我的计算机暴露给一个固定的 IP 地址并转发 1099 和 1100 端口。此解决方案允许其他开发人员“查找”我的服务器并获得有效且可用的代理,但不允许他们导出他们的 IClient。似乎 JVM 尝试将对象导出到其本地网络,并且执行在此处停止。
因此,我尝试-Djava.rmi.server.hostname=my-external-IP
为我的服务器和远程客户端传递 JVM 参数。这样做,exportObject 会ConnectException
向远程 ip 而不是本地 ip 抛出一个。