I've been playing with the new Servlet 3.0 async features with Tomcat 7.0.4. I found this Chat Application, that lets clients hang on GET request to get message updates. This is working just fine when it comes to receiving the messages.
The problem arises when the client is disconnected i.e. the user closes the browser. It seems that the server does not raise IOException
, even though the client has disconnected. The message thread (see the source code from link above) is happily writing to all stored AsyncContext
's output streams.
Is this a Tomcat bug? or am I missing something here? If this is not a bug, then how I'm supposed to detect whether the client has closed the connection?
isClosed() tells you whether you have closed this socket. Until you have, it returns false.
If the server closes the connection after sometime ,how can the client know that the server has closed the connection. [Thomas] You could try periodically pinging the server, and if you get "timed out", then you know that the connection has terminated.
In TCP there is only one way to detect an orderly disconnect, and that is by getting zero as a return value from read()/recv()/recvXXX() when reading. There is also only one reliable way to detect a broken connection: by writing to it.
The client program closes the socket using shutdown() or close() . When this happens, TCP will send a FIN packet to your server. This will show up as a closed socket in your server when you try to read beyond the last byte of data sent by the client. The next read() will probably throw an exception or error condition.
The code there at line 44 - 47 is taking care of it,
} catch(IOException ex) {
System.out.println(ex);
queue.remove(ac);
}
And here too at 75 - 83, using timeout thingie,
req.addAsyncListener(new AsyncListener() {
public void onComplete(AsyncEvent event) throws IOException {
queue.remove(ac);
}
public void onTimeout(AsyncEvent event) throws IOException {
queue.remove(ac);
}
});
EDIT: After getting a little more insight.
setAsyncTimeout()
in the doc, neither here, nor here. So, I think they dropped it completely in the final version due to some unknown valid reasonSo, what I can say, after combining all these fact, that you are trying to work with the thing that is broken in a sense. That also, may be, the reason for different and weird results.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With