Search code examples
javatomcathttpurlconnectionkeep-alive

Tomcat, HTTP Keep-Alive and Java's HttpsUrlConnection


I have two Tomcat servers that need to maintain a persistent connection to cut down on SSL handshaking. One server (the proxy) sits in a DMZ while the other one is safely behind another firewall. The proxy basically just runs a simple servlet that does some sanity checking before forwarding requests over to the secure machine. On an intial request the machines exchange certificates before performing the real work. Therefore I'd like to maintain a persistent connection with a timeout of a few minutes.

To talk to the secure server, the servlet on the proxy uses HttpsUrlConnection. I've set up WireShark and I've noticed that no matter what keepAliveTimeout value I set for connector on the secure machine, the TCP connection gets closed after about 5 or 10 seconds. This number seems to match up with what I've read is the default timeout and how Java handles HTTP Keep-Alive. This link explains that Java honors the Keep-Alive timeout if it is sent by the server, otherwise it uses 5 seconds (direct connections) or 10 seconds (proxy connections) before it closes the connection.

What I'm trying to figure out is how can I force Tomcat to send the Keep-Alive header. Not, Connection: Keep-Alive, but Keep-Alive: timeout=x.

I've experimented with Apache HTTP server and modifying the keepAliveTimeout in httpd.conf does cause the Keep-Alive header to change its timeout value. Furthermore Java does honor this timeout.

UPDATE (12/23/11): After running a few more experiments I tried whipping up some quick and dirty code using Apache's HttpClient (3.1) rather than HttpsUrlConnection. It appears that HttpClient, when set to use Keep-Alive, simply waits for the server to close the connection. I don't know how long it will wait though. I'm shooting to keep the HTTP connection alive for 3 to 5 minutes.


Solution

  • I was able to use HttpClient 3.1 to hold the HTTP connection open for 5 minutes by setting the keepAliveTimeout in the Tomcat connector to 300000. I verified it using WireShark that the server will terminate the connection while HttpClient will simply wait. Subsequent requests through HttpClient reuses the existing TCP connection (avoiding any further SSL handshaking). The key there though is to have a single HttpClient instance (i.e. not creating one each time). This might be obvious to most but I wasn't sure what the API mechanics for HTTPClient would be. In short, create one HttpClient instance and for each request (POST, GET, etc.) create a new PostMethod, GetMethod, etc. This will cause the TCP connection to be reused.