Game Development Reference
In-Depth Information
Long polling is the happy medium between simple AJAX and complex HTTP streaming, also known as
HTTP server push or Comet (see Figure 10-4). Its key advantage is that the client creates only one
connection, which it uses to receive data from the server in real time. Its drawbacks are complexities with
implementation and disharmony with the spirit of HTTP.
Figure 10-4. Network traffic diagram demonstrating streaming
For a long while, Comet was the only option of receiving real-time data from the server without resorting to
third-party plug-ins. With the advent of HTML5, we are given two technologies to do this: WebSockets and
Server-Sent Events.
Server-Sent Events
Server-Sent Events builds on the Comet idea and should replace it in the future (or at least displace long
polling). The client subscribes to server-side events, receiving notifications and certain event-related data
as soon as the event takes place.
As shown in Listing 10-4, simple reception of server messages is organized with just a few strings of
codeā€”no comparison to the bulky logic used in Comet.
Listing 10-4. An example of a simple SSE connection
// Specify new message source
// Note you are using http
var source = new EventSource(' http://sontan.name/stream/');
// Subscribe to messages from the source
source.addEventListener('message', function(e) {
console.log(e.data);
}, false);
The event stream is plain text using text/event-stream as Content-Type. In the simplest case, as shown in
Listing 10-5, it is a string that begins with data: followed the body of the message and ending with two
newlines: \n\n .
Listing 10-5. A single-line message from the server
data: simplest message\n\n
 
Search WWH ::




Custom Search