gpt4 book ai didi

Java RMI 通过互联网

转载 作者:行者123 更新时间:2023-12-02 04:38:23 24 4
gpt4 key购买 nike

我正在用 Java 开发一个游戏,使用 RMI 进行所有网络通信。 RMI 允许我调用服务器上的方法,但这对我来说还不够。我还希望服务器能够在连接的客户端之间传播消息。

我的客户端查找服务器(它的接口(interface)扩展了远程)并在其上注册。它允许服务器知道谁连接了。我的客户还实现了一个扩展 Remote 的接口(interface)。这是我的代码的一部分:

接口(interface)声明:

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)));

此解决方案在本地有效,但当我尝试通过互联网使用它时却无效。

我已设置路由器,将我的计算机暴露给固定 IP 地址并转发 1099 和 1100 端口。此解决方案允许其他开发人员“查找”我的服务器并获取有效且可用的代理,但不允许他们导出其 IClient。看起来 JVM 试图将对象导出到本地网络,但执行到这里就停止了。

因此,我尝试将 -Djava.rmi.server.hostname=my-external-IP JVM 参数传递给我的服务器本地和客户端远程。这样做时,exportObject 会向远程 IP(而不是本地 IP)抛出 ConnectException

最佳答案

算了。通过 Internet 使用回调需要每个客户端配置其防火墙/NAT 盒/任何内容以允许入站连接和可能的端口转发。其中许多根本不可配置,而且许多是由网络管理员运行的,而他们根本不会这样做。

注意,您还必须在固定端口上导出。

关于Java RMI 通过互联网,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16268391/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com