I have the following example of reading from a buffered reader:
while ((inputLine = input.readLine()) != null) {
System.out.println(\"I got a message from
The reader's readLine() will return a string value when it has something read, an empty string when there isn't anything yet, and null when the connection is closed.
I would recommend wrapping a try/catch around your block of code with the IO function and handle errors appropriately.
When the socket on the other end is closed, the reader should return a null string. This is the condition that you are looking for. To handle the exception, wrap the reading loop in a try/catch block.
try {
while ((inputLine = input.readLine()) != null) {
System.out.println("I got a message from a client: " + inputLine);
}
}
catch (IOException e) {
System.err.println("Error: " + e);
}
You might find this tutorial on reading/writing from/to a socket in Java, helpful.
while ((inputLine = input.readLine()) != null) {
Look at each part of the expression:
input.readLine()
Returns a String which will be null if the end of the stream has been reached (or throws an Exception on error).
inputLine = input.readLine()
Assigns this String to inputLine
((inputLine = input.readLine()) != null)
Checks that the String that was assigned is not null (end of stream).