Wednesday, 19 October 2011

HTML5 Server Side Events


Server-Sent Events (SSE) is a standard describing how servers can initiate data transmission towards clients once an initial client connection has been established.

It is commonly used to send message updates or continuous data streams to a browser client and designed to enhance native, cross-browser streaming through a JavaScript API called EventSource, through which a client requests a particular URL in order to receive an event stream.

This means the client can receive a one way fire hose of data from the server for such scenarios as new FX rates, stock prices, new message received, etc.

But I thought we had Web Sockets for this?  Yes, HTML5 does provide Web Sockets but that is for full duplex (bi-directional) data transfer whereas SSE can be used for one way communication from server to client.


In our simple example

  • The client automatically registers for Server Sent Events, setting Id to the current time (in JavaScript)
  • Every 5 seconds the server pushes event data to the client
  • The data, made up of three parts Id, Detail and Timestamp is displayed on the page.
  • A message counter is incremented for each message received.
  • The Server terminates the connection after 10 seconds (after 3 messages)
  • The cycle starts with the client registering for events.


Points of Interest

Notice how in the screenshot only two HTTP GETs were sent from the client to the server data URI (stream.php), one for each connection that was made.  The connection is kept open whilst the 3 events/messages are pushed the client.

Data format

In our example we are using JSON data format within the Event-Stream data format. We also need to set the Content Type of the event to “text/event-stream”.

To be able to set the HTTP header content type, we’ll be using a simple php script:

HTML Source

You can view the page online:

No comments:

Post a Comment