Oracle Blog

Blog for swchan

A Simple Comet Example: Hidden Frame and Long Polling

Recently, there is a great interest in Comet technology.
One can find many interesting articles in Comet Daily.
Comet allows server and client to keep a live connection for communication.
This provides a mechanism for server to update clients, instead of
having classical polling.
In this blog, I am going to share my experience about using Comet
with hidden frame and long polling in
GlassFish v3 Technology
Preview 2 builds.
I try to make example as simple as possible to illustrate the basic
interactions there. If you want to learn more about Comet, then I recommend
Jean-Francois' blogs.

In our case, it writes a Javascript back to client side. This will invoke the Javascript function updateCount in count.html. The onEvent also invokes resumeCometHandler.
This is necessary as the polling connection will be dropped once it is used.

To compile the above Java code, one needs to include javax.javaee\*.jar and grizzly-comet\*.jar in classpath.

Client Code

On client side, I will illustrate the technique of hidden frame.
Basically, the main page will have at least two frames. One of them does the long polling and is hidden from user.
In our case, the index.html consists two frames as follows:

The first frame, which is hidden, is pointed to our Comet Servlet above through GET method.
The second frame is to display the counter and submit button
for incrementing the counter.
The Javascript in count.html is very simple as follows:

One can download the sources and war file from
here,
and deploy the war file.
Using two browsers to access http://localhost:8080/grizzly-comet-hidden/index.html
and click on "Click" button on each browser separately.
Then one sees that counts in both browsers will be updated whenever one
clicks on one of them. The mechanism is outlined as follows:

When the user accesses index.html, a browser will load two frames:

The "hidden" frame accesses our Comet Servlet through GET method. This allows the client to start long polling with server.

The "counter" frame loads a static count.html.

When the user clicks on the button in count.html,
it submits a POST request to our Comet Servlet.
This triggers the CometHandler onEvent method
and redirects back to count.html to display
the count. The onEvent triggers the
updateCount() JavaScript in "counter" frame, which will

Shing Wai,
I'd like to use the DeliverResponse object in Bayeux, but need the clustering support of GlassFish v2ur2 (v3 Prelude does not support clustering yet). What would you recommend?
Thanks and Happy New,
Anthony

With the recent change in domain.xml, can need to enable comet/cometd by adding an attribute enable-comet-support="true" on the http element under protocol. For instance, <network-config>/<protocols>/<protocol name="http-listener-1">/<http enable-comet-support="true" ...>