Server-Sent Events

Introduction

Server-Sent Events communication is a way to receive data from a server without making a request at each time.
In Cendre, you can create SSE servers very simply thanks to its dedicated module.

Create a server page.

Each SSE server will be a .nodejs page. You just have to copy and paste the following code in it.

exports.stream = true;

exports.run = function(c, end)
{
	end('');
	c.server_response.setHeader('Cache-Control', 'no-cache, must-revalidate');
	c.server_response.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
	require(c.m.sse).add(c);
};

Let's say this page is called sse-server.nodejs and is located at the root of your website.

Connection

In a webpage, you can connect to your SSE server with a bit of JavaScript.

var sse_source = new EventSource('/sse-server.nodejs');

Receiving events from the server

To start receiving events, you just have to add an event listener on the EventSource object.

// Getting the connection ID.
var id = '';

sse_source.addEventListener('id', function(event)
{
	id = event.data;
});

// Listen on connection opening.
sse_source.addEventListener('open', function(event)
{
	console.log('Connection established.');
});

// Listen on any message with no event name.
sse_source.addEventListener('message', function(event)
{
	console.log(event.data); // Message content.
});

// Listen on messages with the 'custom' event name.
sse_source.addEventListener('custom', function(event)
{
	console.log(event.data); // Message content.
});

// Listen on errors.
sse_source.addEventListener('error', function(event)
{
	console.log('An error occured.');
});

Sending events to your webpage

From another .nodejs file, you can send events to the webpage connected to your SSE server.
You have to use the connection ID. You can send it as a get parameter for example.

// Requires the sse module.
var sse = require(c.m.sse);

// Sends an anonymous event.
sse.send(c.get.id, 'Hello World !');

// Sends a 'custom' event.
sse.send(c.get.id, 'Hello World !', 'custom');

// Keeps the connection alive.
sse.ping(c.get.id);

Configure

In your configuration file, you can specify a different ID event name or a different time-out for connections if needed.

exports.host.modules.sse.event = 'id';	// Event name for retrieving the connection ID.
exports.host.modules.sse.timeout = 300;	// Connections time-out.

Browser support

Internet Explorer :  No (yes with polyfill)
      Opera 12.14 : Yes
          Firefox : Yes
           Chrome : Yes
           Safari : Yes