Java Reference
In-Depth Information
There are several approaches to implementing Comet that can be grouped into either
streaming or long-polling. This is nicely broken down in an article on IBM developer-
Works. [ 1 ] This article describes how each approach works and provides code samples.
We'll describe the two different approaches at a high level and contrast the technology with
WebSockets. Actually implementing a Comet solution is beyond the scope of this section
and you'll definitely want to use WebSockets.
1 Carbou, Mathieu. “Reverse Ajax, Part 1 : Introduction to Comet.” IBM developerWorks, July 19, 2011, ht-
tp://www.ibm.com/developerworks/library/wa-reverseajax1/ .
Streaming is a technique whereby a long-lived HTTP request is created and messages are
sent back over this connection. There are two approaches to creating this long-lived con-
nection: Forever IFrames and multipart XMLHttpRequests .
With Forever IFrames, the page contains a hidden IFrame tag with an src attribute that
requests content. When the server receives the request for IFrame, it keeps the connection
open and transmits code embedded in <script></script> pairs containing the mes-
sage. The browser executes the code, and the JavaScript snippet delivers the message it
contains.
The other streaming approach, multipart XMLHttpRequests , has the client Java-Script
code set the multipart flag on the XMLHttpRequest . The connection is left open and
the server transmits each message as a multipart response. If you're familiar with multipart
form submissions, this is analogous to multipart form submission in reverse.
Forever IFrames and multipart XMLHttpRequests are both streaming approaches. The
other approach to Comet is HTTP long-polling. With HTTP long-polling, the client opens
an AJAX call to the server. The server hangs onto the connection until there's a response.
Once it writes the response back to the client, the connection is closed. The client then ini-
tiates another AJAX call to the server to wait for another message.
Both streaming and long-polling are essentially hacks. With Forever IFrames there's no
easy way to handle error detection and recovery. Multipart XMLHttpRequests aren't
supported by all browsers. With long-polling there's the chance that you'll miss a message.
What happens if a message arrives after a message has been delivered and closed but be-
fore the client is able to open the next connection? How does a server know when a client
has disappeared so that it doesn't cache messages delivered on reconnect? Using XMLHt-
 
Search WWH ::




Custom Search