Search code examples
javasocketsbufferedreaderjava-io

Sockets: BufferedReader readLine() blocks


I am using BufferedReader.readLine() method to read a response from a remote server (which is written in C and I have no access to source code).

BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
while((line = br.readLine())!=null){
    [...]
}

But it always blocks at the last line until it times out. So I used the following code:

int b;
while(true){
   b = in.read;
   [...]
}

and I found out that the last byte read has an integer value of 13, which I think it is a carriage return, right?

So why the readLine method blocks? How does the server usually signal an end of stream is reached? Thanks.


Solution

  • In the case of a network connection, the stream is terminated when the socket is closed.

    So it is perfectly normal that readLine() blocks until it received an "end of line" or you close manually the connection. When your readLine() receives the last character with the '13' value, the line is read and the loop starts again, waiting for the next line.

    There is no difference between the "last line" and the other lines.

    In order to stop the loop, you must manually close the connection somewhere or wait for the timeout. But without more information about your communication protocol, it is impossible to be more precise about this.