BufferedReader 在 readLine() 上阻塞

BufferedReader Blocking on readLine()

出于某种原因,我无法从服务器上的客户端读取行。客户端能够毫无问题地发送线路,但服务器不会移动超过 第一次 clientIn.readLine() 被调用 。我认为它正在阻塞,但我不知道如何处理它。

当我在没有服务器端循环的情况下发送行时也会发生这种情况。

Client.java

public void run()
{
     try {
        socket = new Socket(ip, port);
        System.out.println("Client connected on port: " + socket.getRemoteSocketAddress());
        //wrap streams for ease 
        BufferedReader serverIn =  new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintWriter serverOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
        System.out.println("starting messages");

        //send messages 
        serverOut.println("hello from: " + socket.getLocalSocketAddress());
        serverOut.println("msg1: " + this.hashCode());
        serverOut.println("msg2: final test");
        //close the connection
        socket.close();

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

Server.java:

public void run()
{
    System.out.println("Server Running on port: " + serverSocket.getLocalPort());
    while(true)
    {
        try {
            //listen for connections
            Socket client = serverSocket.accept();

            //record sockets 
            connections.put(client.getRemoteSocketAddress(), client);

            //wrap streams for ease 
            BufferedReader clientIn = new BufferedReader(new InputStreamReader(client.getInputStream()));
            PrintWriter clientOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())));

            //send messages
            String line = null;
            while((line = clientIn.readLine()) != null)
            {
                System.out.println(line);
            }

            //ends the connection
            client.close();
            System.out.println("Client disconnected");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

您需要 flush() 您的 serverOut 编写器,否则您的消息将保留在 BufferedWriter 的缓冲区中,永远不会发送到服务器。

socket.close();

您正在关闭您应该关闭 PrintWriter:

的套接字
serverOut.close();

当您从下方关闭套接字时,您将丢失 PrintWriter 中的缓冲数据。