gpt4 book ai didi

Java套接字连接超时,在本地工作

转载 作者:行者123 更新时间:2023-12-02 04:01:20 25 4
gpt4 key购买 nike

有问题的代码是这样的:

class Server {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(4001);
Socket s = ss.accept();
// streams, buffer, strings, main loop and socket closing; all works fine
}catch(Exception e) {/*handle*/}
}
}

class Client {
public static void main(String[] args) {
try {
Socket s = new Socket(InetAddress.getByName("24.135.22.219"), 4001); // << Connection fails here.
// streams, buffer, strings, main loop and socket closing; all works fine
}catch(Exception e) {/*handle*/}
}
}

"serverIP" 替换为 InetAddress.getByName(null) 时,在本地一切正常。但是,当它替换为我的 IP 地址时,无法建立连接(即使我禁用 Windows 防火墙),并且收到连接超时错误。

用于测试的文件是here .

最佳答案

您需要将 ServerSocket 绑定(bind)到您尝试连接的同一地址:

ServerSocket ss = new ServerSocket();
ss.bind(new InetSocketAddress("<serverIp>", 4001));
Socket s = ss.accept();

关于Java套接字连接超时,在本地工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34860298/

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