0

我正在尝试编写一个小程序,它打开一个服务器,创建一个连接到该服务器并从中接收消息的客户端。

这是到目前为止的代码

public static void main(String[] args) {
final ServerSocket serverSocket;
try {
    serverSocket = new ServerSocket(12345);
    Thread t = new Thread(){
        public void run(){
                try {
                    Socket server = serverSocket.accept();
                    PrintWriter writer = new PrintWriter(server.getOutputStream(), true);
                    writer.write("Hello World");
                    writer.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        t.start();
        Socket client = new Socket("localhost", 12345);
        BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
        String message = reader.readLine();

        System.out.println("Received " + message);
    } catch (IOException e1) {
        e1.printStackTrace();
    }

}

如果我运行程序,它会一直在 readLine() 中等待 - 很明显客户端没有收到来自服务器的消息。有谁知道为什么这不起作用?

4

2 回答 2

3

您的阅读线程正在等待数据流中的换行符。只需更改要使用的服务器:

writer.write("Hello World\r\n");

你会得到你期望的结果。或者,您可以只关闭服务器套接字,然后readLine在到达数据流末尾时返回。

于 2011-10-17T22:10:32.960 回答
0

您应该将 readline 放在一个循环中,如下所示:

public static void main(String[] args) {
    final ServerSocket serverSocket;
    try {
        serverSocket = new ServerSocket(12345);
        Thread t = new Thread() {
            public void run() {
                try {
                    Socket server = serverSocket.accept();
                    PrintWriter writer = new PrintWriter(server.getOutputStream(), true);
                    writer.write("Hello World");
                    writer.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        t.start();
        Socket client = new Socket("localhost", 12345);
        BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
            // Check this --------------------------------------------------->
            String message = null;
            while ((message = in.readLine()) != null) {   
                    System.out.println("Received " + message);
                    break; //This break will exit the loop when the first message is sent by the server
            }

    } catch (IOException e1) {
        e1.printStackTrace();
    }

}

您可以阅读本文档以获得进一步的解释:http: //download.oracle.com/javase/tutorial/networking/sockets/

于 2011-10-17T22:18:03.340 回答