Search code examples
javaiobufferedreader

BufferedReader blocking at read()


Im trying to create a simple chat program, with a "server" and a client, now my problem is that the program blocks while reading messages from the server to the client and vice-versa. This example features the problem with messages from Client to Server.

Example of what I have on the server side:

private Reader input;
private Writer output;

try {

        server = new ServerSocket(this.port);

        while (true) {

            Socket connection = server.accept();

            serverDisplay("We have a connection");

            input = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            output = new BufferedWriter(new OutputStreamWriter(
                    connection.getOutputStream()));

            int c;
            StringBuffer sb = new StringBuffer();

            // This is where it blocks, the input stream should return -1 at the end of the
            // stream and break the loop, but it doesnt
            while ((c = input.read()) != -1) {
                sb.append((char) c);
            }
            serverDisplay(sb.toString());
        }

    } catch (IOException e) {
        System.out.println("IO ex in the server");
    }

For sending message on the client side I have the following code:

output = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));

and

private void sendMessage(String message) {
    displayMessage(message);

    try {
        output.write(message);
        output.flush();
    } catch (IOException e) {
        System.out.println("IO ex at sendMessage client");
    }

}

It reads all the characters I send (from client to server; confirmed with Sys out) but when it is supposed to read the end of the stream (-1) it hangs there.

I have tried to print the "c" inside the while loop to see the value it returns and it simply doesn't go in the loop neither does it break it, it just hangs there.

I'm aware there are a few questions already related to this subject but I haven't found the solution to my problem in any of them.

Oddly enough (at least for me) if I use:

output = new ObjectOutputStream(connection.getOutputStream());
input = new ObjectInputStream(connection.getInputStream());

and:

while ((message = (String) input.readObject()) != null)

Instead of:

input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
output = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));

And:

while ((c = input.read()) != -1) 

The hole thing works. However this is not how I want to do it, and by reading the API's of the BufferedReader/Writer, Input/OutputStreamWriter I would think my code should work.

Thank you in advance.


Solution

  • The end of stream on the receiver side isn't reached until the sending stream (or entire socket) is closed.

    output.close() on the send side will cause the receive side to see end of stream.

    If you need to use the stream for multiple messages, you'll need to introduce a frame structure in to your application protocol so that receiver can determine message boundaries. This can be as simple as prefixing the length of the message in bytes to each message.

    Since you are using a String as your entire message. You can use DataInputStream and DataOutputStream stream decorators to frame the message for you with readUTF() and writeUTF(String). writeUTF(String) basically frames the string by writing its length to stream before writing the string. readUTF() then reads this length and then knows how much data it needs to read off the stream before returning.

    Example:

    Output:

    DataOutputStream output = new DataOutputStream(connection.getOutputStream());
    
    private void sendMessage(String message) {
        displayMessage(message);
    
        try {
            output.writeUTF(message);
            output.flush();
        } catch (IOException e) {
            System.out.println("IO ex at sendMessage client");
        }
    
    }
    

    Input:

    DataInputStream input = new DataInputStream(connection.getInputStream());
    
    String message = input.readUTF();
    
    serverDispaly(message);