Reputation: 55
It sounds like an odd question, but I've been toying around with Server/Client Java work using Sockets. Something interesting I found is that when I ran a separate thread for the client to read lines from the server through the following code:
String servIn = null;
boolean isFinished = false;
while(!isFinished){
servIn = reader.readLine();
System.out.println(servIn);
}
When the all the reading I needed done ended (in other words, I no longer wrote to the Socket in the code), this code produced an endless stream of "null". After doing a bit of research, based on Reading from a BufferedReader (readLine) returns null?, I concluded that once all the methods had run, the end of stream was reached.
I found this odd, because I never explicitly told the stream to close at the end, and there are times in the code when it needs to hang on (BufferedReader, from a Socket) readLine() to wait for a (PrintWriter, from a Socket) writer.println() on another end of the code, and vice versa. From what I understand of readLine() and println(), they seem to wait until the respective other method is ready. This makes me confused, because it seems to me that at the end of the code, it should have just stayed at readLine() instead of spitting out "null"s. Does the JVM or class Socket simply determine when the OutputStream has been ended, by looking ahead and seeing that no more writing through println() will occur?
Is my interpretation of println() and readLine() from a Socket's stream correct, and if so, what causes the sudden shift to spitting "null"s? Thanks in advance!
Upvotes: 1
Views: 1826
Reputation: 310884
What triggers a Socket's InputStream to close (or reach end of stream), and simply yield null?
InputStream
to close is calling close()
on it, or on its underlying socket.InputStream
to reach end of stream is reading to end of file in the case of a file, or the peer closing the connection in the case of a socket.InputStream
doesn't return null, but BufferedReader.readLine()
does, when you reach end of stream, as it says in the Javadoc.Possibly you are unaware that closing either the input stream or output stream of a socket will close the socket.
this code produced an endless stream of "null"
That's because you ignored end of stream. When you get this condition you should close the socket and stop reading.
Upvotes: 4