Server-Sent Events (SSE) is a standard describing how servers can initiate data transmission towards clients once an initial client connection has been established.
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
- 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.
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:
You can view the page online: http://stevenhollidge.com/html5demos/server-sent-events/