HTML and CSS Reference
In-Depth Information
13.4 The Comet Client
Although long polling offers good latency and near-constant connections, it also
comes with limitations. The most serious limitation is that of number of concurrent
http connections to any given host in most browsers. Older browsers ship with a
maximum of 2 concurrent connections by default (even though it can be changed
by the user), whereas newer browsers can default to as many as 8. In any case,
the connection limit is important. If you deploy an interface that uses long polling
and a user opens the interface in two tabs, he will wait indefinitely for the third
tab—no HTML, images, or CSS can be downloaded at all, because the poller is
currently using the 2 available connections. Add the fact that XMLHttpRequest
cannot be used for cross-domain requests, and you have a potential problem on your
hands.
This means that long polling should be used consciously. It also means that
keeping more than a single long polling connection in a single page is not a viable
approach. To reliably handle data from multiple sources, we need to pipe all mes-
sages from the server through the same connection, and use a client that can help
delegate the data.
In this section we will implement a client that acts as a proxy for the server. It will
poll a given URL for data and allow JavaScript objects to observe different topics.
Whenever data arrive from the server, the client extracts messages by topic and
notifies respective observers. This way, we can limit ourselves to a single connection,
yet still receive messages relating to a wide range of topics.
The client will use the observable object developed in Chapter 11, The
Observer Pattern, to handle observers and the ajax.poll interface we just imple-
mented to handle the server connection. In other words, the client is a thin piece of
glue to simplify working with server-side events.
13.4.1 Messaging Format
For this example we will keep the messaging format used between the server and
the client very simple. We want client-side objects to be able to observe a single
topic, much like the observable objects did, and be called with a single object
as argument every time new data is available. The simplest solution to this problem
seems to be to send JSON data from the server. Each response sends back an object
whose property names are topics, and their values are arrays of data related to that
topic. Listing 13.42 shows an example response from the server.
 
 
Search WWH ::




Custom Search