Detecting client disconnect in tomcat servlet?

How can I detect that the client side of a tomcat servlet request has disconnected? I've read that I should do a response.getOutputStream().print(), then a response.getOutputStream().flush() and catch an IOException, but is there a way I can detect this without writing any data?

EDIT:

The servlet sends out a data stream that doesn't necessarily end, but doesn't necessarily have any data flowing through it (it's a stream of real time events). I need to actually detect when the client disconnects because I have some cleanup I have to do at that point (resources to release, etcetera). If I have the HttpServletRequest available, will trying to read from that throw an IOException if the client disconnects?


Solution 1:

is there a way I can detect this without writing any data?

No because there isn't a way in TCP/IP to detect it without writing any data.

Don't worry about it. Just complete the request actions and write the response. If the client has disappeared, that will cause an IOException: connection reset, which will be thrown into the servlet container. Nothing you have to do about that.

Solution 2:

I need to actually detect when the client disconnects because I have some cleanup I have to do at that point (resources to release, etcetera).

There the finally block is for. It will be executed regardless of the outcome. E.g.

OutputStream output = null;
try {
    output = response.getOutputStream();
    // ...
    output.flush();
    // ...
} finally {
    // Do your cleanup here.
}

If I have the HttpServletRequest available, will trying to read from that throw an IOException if the client disconnects?

Depends on how you're reading from it and how much of request body is already in server memory. In case of normal form encoded requests, whenever you call getParameter() beforehand, it will usually be fully parsed and stored in server memory. Calling the getInputStream() won't be useful at all. Better do it on the response instead.

Solution 3:

Have you tried to flush the buffer of the response: response.flushBuffer(); Seems to throw an IOException when the client disconnected.