如何连接到运行Java服务器的其他计算机?

时间:2012-03-26 20:46:58

标签: java

我用Java创建了一个简单的echo服务器。当我在本地尝试时,它可以正常工作。但是,当我尝试使用服务器运行的IP地址和端口号从不同的计算机连接它时,它永远不会连接。是否还有其他事情要从另一台计算机连接到服务器?

import java.net.Socket;
import java.net.ServerSocket;

public class EchoServer {

    public static void main(String[] args) throws Exception {

        // create socket
        int port = 4444;
        ServerSocket serverSocket = new ServerSocket(port);
        System.err.println("Started server on port " + port);

        // repeatedly wait for connections, and process
        while (true) {

            // a "blocking" call which waits until a connection is requested
            Socket clientSocket = serverSocket.accept();
            System.err.println("Accepted connection from client");

            // open up IO streams
            In  in  = new In (clientSocket);
            Out out = new Out(clientSocket);

            // waits for data and reads it in until connection dies
            // readLine() blocks until the server receives a new line from client
            String s;
            while ((s = in.readLine()) != null) {
                out.println(s);
            }

            // close IO streams, then socket
            System.err.println("Closing connection with client");
            out.close();
            in.close();
            clientSocket.close();
        }
    }
}

2 个答案:

答案 0 :(得分:1)

请检查以下事项。

  1. 服务器计算机是否位于网络代理之后?

  2. 是否具有可从中访问的独立公共IP地址 任何地方或者,它是否有内部IP,可以通过LAN访问它?

  3. 确保FireWalls端口4444有例外。或者您可以在客户端和服务器中关闭它。

  4. 如果没有帮助,请发布您获得的例外(通过编辑问题)。或者服务器程序只是冻结而没有任何错误?

答案 1 :(得分:0)

如果这是在您的LAN上,请参阅运行您的EchoServer的机器名称(实际的机器名称,我相信他们会在Sun Tutorial上以这种方式执行此操作,发布此echo服务器的运行正确吗?)。如果这样做有用,它将有助于解决问题。