Follow up on A Simple Comet Example: Long Polling vs Http Streaming
Wednesday Apr 23, 2008
In my previous comet blog, A Simple Comet Example: Hidden Frame and Long Polling", I illustrate comet by using a simple example of two frames. While it is good for illustration, there is a limitation. If you try to use two different browsers to access the counter and click really fast, then you may notice that one of the counter may be updated and then immediately changes to blank. This is because the comet response may come before the response of the http post. This is more significant in the case of Http Streaming. In this blog, we will explain how to resolve "blank problem" and change the example to use Http Streaming instead of Long Polling.
One More Frame
The "counter blank" problem can be solved easily by extracting the
post action and put it in a different frame
(button.html). In other words, we only keep the
display related stuff in count.html.
In this case, post request is sent from button.html,
not from count.html. And hence, count.html
will only be updated by JavaScript only. (In contrast
with my previous blog, the count.html can also be
updated by Http Response.)
Now, in index.html, there will three frames as follows:
<iframe name="hidden" src="hidden_comet"
frameborder="0" height="0" width="100%"><iframe>
<iframe name="counter"
src="count.html" frameborder="0" height="70%"
width="100%"><iframe>
<iframe name="button"
src="button.html" frameborder="0" height="30%"
width="100%"><iframe>
The next thing we need to do is to update one line of
Java code in the doPost of the servlet to
redirect back to button.html rather than
count.html.
req.getRequestDispatcher("button.html").forward(req, res);
You can download the updated sample here.
Http Streaming
Http Streaming is different from Long Polling by keeping the connection (until expiration) between client and server even after it delivers the data. In general, this will perform better. With the fix in the previous section, we can modify our example easily to Http Streaming by commenting out the following
event.getCometContext().resumeCometHandler(this);inHiddenCometHandle.java
In this case, the server will not resume the connection.parent.hidden.location.href = "hidden_comet"inupdateCount JavaScript
In this case, the browser will not reload the hidden frame again.










