Tomcat Servlet - How your Servlet or Filter can tell if the client closed its end of the HTTP connection

 
How can my Servlet or Filter tell if the client closed its end of the HTTP connection?

When the client disconnects, and your servlet tries to write to the output stream, Tomcat will throw a ClientAbortException (you may have already seen this):

http://tomcat.apache.org/tomcat-6.0-doc/api/org/apache/catalina/connector/ClientAbortException.html

Tomcat appears to throw this exception only when you write some bytes to the output stream, or when you flush the output stream, and the client already closed its end of the connection. You can try flushing the output stream periodically and see if doing so throws this exception. You can flush at any time, even if you have written zero bytes. Try it like this:

try {
    response.getOutputStream().flush();
} catch (ClientAbortException e) {
    // The client already closed its end of the TCP connection.
}

The first time you call flush, it will send the HTTP response headers to the client, so you must set the headers before flushing.

Comments on this post:
 #

I think this article needs to be expanded a bit. Please help!

 

Post new comment

The content of this field is kept private and will not be shown publicly.

Download Tcat Server - Tomcat Simplified

Develop, diagnose, manage, configure, and deploy your Apache Tomcat applications with ease, and break free from bloated legacy JEE app servers. Built on 100% Tomcat, with no changes to the core code, Tcat Server is free for developers, and there is no commitment required. Try it now, risk-free! 
 

click thumbnail to enlarge

Link to this page