有问题的代码是:
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。
答案 0 :(得分:2)
您需要将ServerSocket
绑定到尝试连接的同一地址:
ServerSocket ss = new ServerSocket();
ss.bind(new InetSocketAddress("<serverIp>", 4001));
Socket s = ss.accept();