Java套接字连接超时,适用于本地

时间:2016-01-18 17:09:16

标签: java sockets

有问题的代码是:

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

1 个答案:

答案 0 :(得分:2)

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

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