gpt4 book ai didi

java - 为什么套接字不使用 ip 而不是 localhost 连接?

转载 作者:行者123 更新时间:2023-12-03 11:55:20 25 4
gpt4 key购买 nike

我正在尝试通过 IP 地址连接到服务器,但它不起作用。两者都在同一台机器上,当我将 ipAddress 更改为 localhost 时,它可以工作。那会是什么原因呢?

try {
String ipAddress = "46.155.17.100";
int port = 8082;

// Create a socket to connect to the server
socket = new Socket(ipAddress, port);

toServer = new ObjectOutputStream(socket.getOutputStream());

fromServer = new ObjectInputStream(socket.getInputStream());

} catch (Exception ex) {
connected = false;
try {
if (socket != null) {
socket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

编辑:当我将连接从 WiFi 更改为互联网电缆时,套接字与新的 IP 地址连接。但我不知道为什么:(

最佳答案

I am trying to connect to server via ip address but it does not work. Both are in the same machine and when I change ipAddress to localhost it works. What would be the reason for that?



原因是服务器代码中的 ServerSocket 未绑定(bind)到您尝试从客户端连接的 IP 地址。因此,在这种情况下,ServerSocket 绑定(bind)到默认环回地址,即 localhost127.0.0.1 .

您需要编辑服务器端代码以在构造函数中将 ServerSocket 的 IP 地址与 IP( 46.155.17.100 ) 绑定(bind)或稍后绑定(bind)。这将通过将 ServerSocket 初始化替换为以下内容来完成:
// int port = 4444, backlog = 5;
String bindaddr = "46.155.17.100";
ServerSocket server = new ServerSocket(port,backlog,InetAddress.getByName(bindAddr));
// your server-side code continues below.

关于java - 为什么套接字不使用 ip 而不是 localhost 连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37420237/

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