我正在使用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;
//...
}
Run Code Online (Sandbox Code Playgroud)
服务器端:
//int RMIPort = 1099, ServerPort = 1100;
IServer Server = new RMIServer();
IServer Proxy = (IServer) UnicastRemoteObject.exportObject(Server, ServerPort);
LocateRegistry.createRegistry(RMIPort).rebind("//" + LocalIP + ":" +
RMIPort + "/xxx", Proxy);
Run Code Online (Sandbox Code Playgroud)
客户端:
//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)));
Run Code Online (Sandbox Code Playgroud)
此解决方案适用于本地,但在我尝试通过Internet使用时却不行.
我已经设置了我的路由器以将我的计算机暴露给修复的IP地址并转发1099和1100端口.此解决方案允许其他开发人员"查找"我的服务器并获得有效且可用的代理,但它不允许他们导出他们的IClient.似乎JVM尝试将对象导出到其本地网络,并且执行在此处停止.
所以,我试图将-Djava.rmi.server.hostname=my-external-IP
JVM参数传递给我的服务器本地和远程客户端.这样做,exportObject会将a抛出ConnectException
到远程ip而不是本地ip.
算了吧.通过Internet使用回调需要每个客户端配置他的防火墙/ NAT盒/无论允许入站连接和可能的端口转发.其中许多根本不可配置,其中许多是由网络管理员运行的,他们不会这样做.
注意,您还必须在固定端口上导出.
归档时间: |
|
查看次数: |
4590 次 |
最近记录: |