I am a bit confused as to what is going on here. Going through Head First Java and I am making a multithreaded server. The part I don't understand is here, where reader is a BufferedReader chained to a InputStream(socket.getInputStream()):
class IncomingReader implements Runnable {
public void run() {
String message;
try {
while ((message = reader.readLine()) != null){
System.out.println("client read " + message);
incoming.append(message + "\n");
}
in particular how does the
while ((message = reader.readLine()) != null)
activate?
What I mean is, if there is no input coming from the server, shouldn't it == null, and if it does not, does the readLine() method itself have some sort of loop that detects data from the server's stream?
I understand that readLine() "blocks" the while loop from activating until it returns a line. My question is, how does it detect that there is something in the inputstream, how does it know when it becomes null?
My question is, how does it detect that there is something in the inputstream, how does it know when it becomes null?
This is more to do with the InputStream
from socket.getInputStream()
than BufferedReader
, really. Any call to InputStream.read()
will block until there's data available, unless the stream is closed. So if the server isn't providing any data, but the socket is still open, the call will block.
If the connection is closed (by either end) then any remaining data will be read, and then future read
calls will return -1 to indicate that the stream has been closed.
BufferedReader.readLine()
will only return null
when the underlying reader returns that there will be no more data, which in the case of InputStreamReader
will only happen if the underlying stream has been closed.
See more on this question at Stackoverflow