gpt4 book ai didi

通过 LAN 使用 TCP/IP 进行 Java 聊天

转载 作者:可可西里 更新时间:2023-11-01 02:49:15 25 4
gpt4 key购买 nike

我开发了一个在 Java 中使用 TCP/IP 聊天的应用程序。到目前为止,它在同一台机器上运行服务器和客户端时完成了工作,但是我想让它在 LAN 上工作。

我发现我应该在我的路由器上使用端口转发,用于我在客户端和服务器中使用的相同端口,并将它转发到我的机器(将是服务器)的 IP。我还发现我应该小心防火墙。

在我的原始媒体集线器路由器上,我使用 (4444) 将端口转发到我机器的本地 IP (192.168.0.21) 的 TCP 协议(protocol)。我还确保没有端口被阻止。

对于防火墙,我已确保未启用 Windows 防火墙并关闭了我的卡巴斯基反病毒防火墙。

到目前为止,这还不允许我通过 LAN 与我的 vmware 机器进行通信。

这里是socket和server socket的代码;

客户:

int portNumber = 4444;
InetAddress host = InetAddress.getLocalHost(); // I also did try changing the host to a String and making host = InetAddress.getLocalHost().getHostAddress();
Socket link = new Socket(host, portNumber);

服务器:

int portNumber = 4444;
ServerSocket serverSocket = new ServerSocket(portNumber);
link = serverSocket.accept();

知道我做错了什么,或者遗漏了什么吗?

最佳答案

使用该代码 (InetAddress host = InetAddress.getLocalHost();),您的客户端将始终联系本地主机,这显然不是您想要的(但解释为什么它在本地工作...

请问官方Oracle tutorial关于客户端-服务器通信?

假设您的远程系统的 IP 地址是 192.168.0.100,您的代码将是

int portNumber = 4444;
String host = "192.168.0.100"; // Socket also has a constructor that accepts
// as String where you can either input a hostname or
// an IP address
Socket link = new Socket(host, portNumber);

套接字 Javadoc here

编辑:您程序中的主要缺陷是您使用了 InetAddress.getLocalHost(),根据 Javadoc

Returns the address of the local host. This is achieved by retrieving the name of the host from the system, then resolving that name into an InetAddress.

强调我的。所以,是的,您的程序将在本地计算机上运行,​​但不能在远程计算机上运行。我的回答的要点是不是我使用字符串,而是我使用本地主机。 ..

关于通过 LAN 使用 TCP/IP 进行 Java 聊天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19662866/

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