简体   繁体   中英

TCP socket: Why BufferedReader.readLine() get NULL?

I have a classic Java client/server app, where client and server exchange messages by a TCP connection.

When one elemement, let's call it Receiver (no matter if client or server), has to receive a message, it listens and waits for a message coming from the other element, let's call it Sender. The receiver implements it by the following code:

BufferedReader myBufferedReader = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
receivedMessageCompleto = myBufferedReader.readLine();

The sender, after some time, will send a text message implementing the following code:

String messageCompleto = "whatever text";
String packetSend = messageCompleto + '\n' ;  
DataOutputStream myDataOutputStream = new DataOutputStream(mySocket.getOutputStream());
myDataOutputStream.writeBytes(packetSend ); 

The probelm is: in some cases "myBufferedReader.readLine()" get null value, but I'm quite sure that the sender didn't send a message NULL. The question is: why?

According to my understanding the Receiver should remain blocked until it receives something (let's consider that timeout is set to infinite), then "myBufferedReader.readLine()" should return a value only when something arrives. The point is that I'm sure that the sender didn't send a null message.

Any idea???

Thank you very much in advance Fausto

public String readLine()
                throws IOException

Reads a line of text. A line is considered to be terminated by any one of a line feed ('\\n'), a carriage return ('\\r'), or a carriage return followed immediately by a linefeed.

Returns:

A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

Basically you get null if the underlying stream hits EOF.

As it says in the documentation for the readLine method :

Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

So, in your case, end-of-stream has been reached. Probably, the remote end of the socket was closed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM