Comet y Server Sent-Events

Comet is a web application architecture in which a long-held HTTP request allows a web server to push data to a browser, without the browser explicitly requesting it.

In Ajax the client pulls data from the server. With Comet the server pushes data to the client.

Other names for Comet are

  1. Server Push
  2. Ajax Push
  3. HTTP Streaming

Server Sent Events defines a simple Comet API in the form of a EventSource object. Server-Sent Events (SSE) is a standard describing how servers can initiate data transmission towards clients once an initial client connection has been established.

Server-Sent Events

The Server-Sent Events draft standard defines an EventSource object that makes Comet applications38.1 trivial to write.

Simply pass a URL to the EventSource() constructor and then listen for message events on the returned object:

var ticker = new EventSource("/stockprices"); 
ticker.onmessage = function(e) {
  var type = e.type; 
  var data = e.data;

  // Now process the event type and event data strings. 
}

The Server-Sent Event protocol

The Server-Sent Event protocol is straightforward:

  1. The client initiates a connection to the server (when it creates the EventSource object) and the server keeps this connection open.

  2. When an event occurs, the server writes lines of text to the connection.

  3. An event going over the wire might look like this:
    event: bid    # sets the type of the event object
    data: GOOG    # sets the data property
    data: 999     # appends a newline and more data
                  # a blank line triggers the message event
    

  4. There are some additional details to the protocol that allow events to be given IDs and allow a reconnecting client to tell the server what the ID of the last event it received was, so that a server can resend any events it missed.



Subsecciones
Casiano Rodriguez León 2015-01-07