ReadRine()上的BufferedReader阻塞

时间:2018-04-17 05:19:54

标签: java sockets bufferedreader printwriter

由于某种原因,我无法从服务器上的客户端读取行。客户端能够毫无问题地发送行,但服务器不会超过第一次调用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();
        }
    }
}

2 个答案:

答案 0 :(得分:5)

socket.close();

您正在关闭应关闭PrintWriter

的套接字
serverOut.close();

当你从它下面关闭套接字时,你在PrintWriter中丢失了缓冲数据。

答案 1 :(得分:4)

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