I use getInputStream().read()
to check if client has disconnected from the server. It works but the read()
function, as it states in documentation, blocks the first letter of message. So instead of printing "Hello", it prints "ello". How can I make the read()
function 'let go' of the first letter?
Here is the following server code to wait for input:
while(true)
{
if(socket.getInputStream().read()==-1)//if no response
break;
String msg = bufferedReader.readLine();
if(msg!=null) {
System.out.println("Received message: " msg);
}
}
If there is no way to go around that, what's the alternative to getInputStream().read()
to detect client disconnection?
CodePudding user response:
The right approach is to not use the separate read() at all. Simply handle readLine() telling you the underlying connection is gone.
For a robust solution, there are two cases you should handle:
readLine() returns null; this is 'normal end of stream' and I'd expect it to happen if the client closed the connection cleanly.
readLine() throws an IOException, which you need try-catch to deal with. This can happen if the connection is terminated abruptly, possibly if the client exits without closing the connection.
It's for you to decide whether those two possibilities are treated identically, based in your program requirements.