BufferedReader Lock on readLine ()

For some reason, I cannot read lines from the client on the server. The client can send lines without problems, but the server will not move past the first time clientIn.readLine () is called . I guess it blocks, but I don’t know how to deal with it.

This also happened when I sent lines without a loop on the server side.

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();
        }
    }
}
+4
source share
2 answers
socket.close();

You close the socket, where you should close PrintWriter:

serverOut.close();

You lose buffered data in PrintWriterwhen you close the socket from under it.

+4
source

flush() serverOut, BufferedWriter .

+2

Source: https://habr.com/ru/post/1696243/


All Articles