客户端只能在同一台计算机上连接到服务器

Client can only connect to server when on the same computer

我正在尝试创建多人 java 游戏并决定使用 java 套接字服务器。当 "client" 在我的计算机上都是 运行 时,它们能够完美地连接并与服务器通信,但是当我将客户端文件发送到另一台计算机(连接到同一网络)时,它是无法连接到服务器,我不知道为什么。我 运行 cmd 并习惯了代码 netstat -a 并且能够确认服务器正在侦听 127.0.0.1:3251 所以我相信问题出在客户端上。

服务器是这样创建的:

    try {
        this.serverSocket = new ServerSocket();
        this.serverSocket.bind(new InetSocketAddress("localhost",port)); //port is 3251
        window.show("SERVER: " + "Created On Port: " + port);
    } catch (IOException e) {
        window.show("SERVER: " + e.getMessage());
        window.show("SERVER: " + "Unable To Create Server :(");
    }

这是客户端连接的方式:

    try {
        socket = new Socket("localhost", 3251);
    } catch (IOException e) {
        e.printStackTrace();
    }

当服务器接受连接时,它会创建一个新线程:

        Socket socket = this.serverSocket.accept();
        ServerThread serverThread = new ServerThread(socket);
        serverThread.start();
    try {
    socket = new Socket("localhost", 3251);
} catch (IOException e) {
    e.printStackTrace();
}

"localhost" 表示您的客户端计算机正在同一台计算机上查找服务器。这应该是服务器 ip,即 192.168.0.2 或其他东西。

你有两个问题:

  1. 您正在服务器上创建 this.serverSocket.bind(new InetSocketAddress("localhost",port));。这将创建一个服务器 localhost 解析到的 IP 地址上的套接字。这可能是个问题。在大多数主机上 localhost 将解析为 127.0.0.1 环回地址和您的 服务器套接字只会听那个。为了能够听到所有 该机器上的 NIC 使用 new InetSocketAddress(port) see the java doc 作为此构造函数。或者发现并使用服务器的特定主机名。
  2. 就像@Nick Eu 在客户端上指出的那样,您正在尝试连接到 localhost 上的服务器。您需要有一种方法来配置您的客户端,以便它知道服务器在哪里并使用它。

进一步澄清: A socket is a IP:Port that is used for communication. Say a host has two NIC's with IP's 192.168.2.1 and 10.0.0.2. Now if you bind server socket (say 8000) to the 192.168.2.1 IP. This port will be only accessible by using this combination 192.168.2.1:8000, similarly if you bind it to the 10.0.0.2 IP it will be accessible only through that IP. And if you bind localhost (aka Loopback address) 只有该主机上的客户端才能访问它。如果您想要 运行 仅限于该主机上的客户端的服务器,这将很有用。