Fernando
Fernando

Reputation: 7905

BufferedReader is not blocking in readLine

I'm creating a networked game in Java using the Sockets api, and got the following problem:

When the app starts the server socket starts listening and spawns a new Thread for each new client (basic stuff, doesn't need to show this code).

Then the client starts the conversation, sending the String "LOGIN". The server receives it and responds with "LOGIN_OK". Now the conversation is over, but the console keeps printing LOGIN_OK (which happens on the client).

Why this happens? readLine() is not supposed to block? Thanks for any clarification!

EDIT: The problem was in the client loop. The client is sending the server's response back to the server! Just commented out that line solved it!

Server loop

public void run()
    {
        String fromClient = null;

        try {
            while ((fromClient = in.readLine()) != null) {
                System.out.println(fromClient);
                String response = SessionProtocol.handleInput(fromClient);

                out.println(response);
                Thread.sleep(50L);
            }

        } catch(IOException ex){ex.printStackTrace();}  
          catch(InterruptedException ex){ex.printStackTrace();}
    }

Client loop

public void run()
    {
        String fromServer = null;

        try {
            while ((fromServer = in.readLine()) != null) {
                System.out.println(fromServer);
                String response = SessionProtocol.handleInput(fromServer);
                 // next line causes the problem
                //out.println(response);
                Thread.sleep(50L);
            }

        } catch(IOException ex){ex.printStackTrace();}  
          catch(InterruptedException ex){ex.printStackTrace();}
    }

Upvotes: 0

Views: 1897

Answers (2)

kevmo314
kevmo314

Reputation: 4317

Yes, readLine() is blocking.

Your in.readLine() reads until the next \n character, regardless of if there's any text before it or not. Since you're calling out.println(), you're appending a \n to your output, regardless of if response is empty or not.

Thus, each iteration of the loop on both the client and server receive a newline and output a newline, which is why it seems like it's not blocking.

Upvotes: 1

Eugen
Eugen

Reputation: 2380

Assuming out.println() writes the message to the output stream of the communication socket it seems you have 2 problems:

  1. Client and server send each other messages continuously, i.e. each loop iteration ends with out.println(response).
  2. Check the logic in case SessionProtocol.handleInput() on the client receives 'LOGIN_OK'. Is it an empty message or some other message? Same check must be done for the server part. You might be sending LOGIN/LOGIN_OK message continuously..

Upvotes: 0

Related Questions