Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BufferedReader Blocking on readLine()

For some reason I am not able to read lines from the client on the server. The client is able to send lines without a problem but the server wont move past the first time clientIn.readLine() is called. I assume it is blocking but I don't know how to deal with it.

This also occurred when I sent lines without the server side loop.

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();
        }
    }
}
like image 495
swiftsword94 Avatar asked Mar 29 '26 17:03

swiftsword94


1 Answers

socket.close();

You are closing the socket where you should be closing the PrintWriter:

serverOut.close();

You're losing buffered data in the PrintWriter when you close the socket out from under it.

like image 98
user207421 Avatar answered Mar 31 '26 09:03

user207421



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!