Jim Driscoll's Blog

Notes on Technology and the Web

Solving the Comet timeout problem

leave a comment »

In my previous blog, I mentioned that I didn’t like the hack of reloading the iframe via the post action – it’s hacky, and it’s not hard to imagine it messing things up in a more complex program.

Turns out the answer is both easy and blindingly obvious once you think of it: the iframe onload event. And while we’re add it, we’ll add a onerror event too.

In my previous program, I had had a hidden iframe, and on every update, I would reset the source for the iframe using the location property.

We’ll still do that, but add a new function:

       <iframe name="hidden" src="CometCount" frameborder="0" height="0" width="100%"
       onload="restartPoll()" onerror="restartPoll()" ></iframe>

Note the onload and onerror events – whenever the server closes the connection, these will be called. And here’s the function that’s called:

            var retries = 0;
            function restartPoll() {
                if (retries++ > 10) {
                    alert("The connection has errored out too many times");                    
                } else {
                    hidden.location = url;                    

Also, I’ve added a retry limit in there – it wouldn’t do to have the client go into a fatal spin just because the server is down.

Now when the server closes the connection (from a timeout, or an error), the client will continue to function, automatically calling back into the server. Not a solution you’ll want for every situation, but useful enough, especially for our small example.

Lastly, there was a bug in my previous version under IE – sorry about that. It turns out that if you send a POST via IE, you need to have a content body, or IE gets fussy. The fix is to change the line


I’ve uploaded new versions of the files index.html and CometCount.java, so you can see the complete code in context.

(This article was originally published on my java.net blog on May 5, 2008.)


Written by jamesgdriscoll

February 9, 2010 at 6:22 PM

Posted in comet, Java, web

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: