有问题的代码是这样的:
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防火墙),也会出现Connection timed out
错误。用于测试的文件为here。
最佳答案
您需要将ServerSocket
绑定到尝试连接到的地址:
ServerSocket ss = new ServerSocket();
ss.bind(new InetSocketAddress("<serverIp>", 4001));
Socket s = ss.accept();
关于java - Java套接字连接超时,适用于本地,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34860298/