With the Total.js framework, you can create an HTTP route for Server-Sent Events, or you can connect easily to another server with implemented Server-Sent Events.
Route for Server-Sent Events
Server-side implementation:
exports.install = function() {
ROUTE('GET /sse/', serversentevents, ['sse']);
};
function serversentevents() {
var self = this;
var lasteventid = self.sseID || '0';
var counter = U.parseInt(lasteventid);
var indexer = 0; var interval = setInterval(function() {
// Closes client after 10 seconds
if (indexer++ > 10) {
self.close();
clearInterval(interval);
} else {
// Sends data to the client
if (!self.sse({ counter: counter++, message: GUID() }, null, counter)) {
// Something wrong
// Client closed
clearInterval(interval);
}
} }, 1000);
}
Client-side (web browser) implementation:
var sse = new EventSource('/sse/');
sse.onmessage = function(ev)
{
// A message
console.log('Message:', ev.data);
};
sse.onerror = function(e) {
// Some error
console.log('Error:', e);
};
Capture Server-Sent Events on the server-side
With the Total.js framework is very easy to handle messages from another server with implemented Server-Sent Events functionality. For example, the code below captures messages from another HTTP server:
var opt = {};
opt.url = 'http://127.0.0.1:8000/sse/';
opt.custom = true;
opt.headers = { accept: 'text/event-stream' };
opt.timeout = 0;
opt.callback = function(err, response)
{
response.stream.on('data', U.streamer('\n\n', function(chunk)
{
var lines = chunk.toString('utf8').split('\n');
var msg = {}; // Server sent events parser
for (var line of lines) {
var index = line ? line.indexOf(':') : -1;
if (index !== -1) {
var key = line.substring(0, index);
var val = line.substring(index + 2);
switch (key) {
case 'data':
val = val.parseJSON();
break;
case 'retry':
val = +val;
break;
}
msg[key] = val;
}
}
// msg.id {String}
// msg.data {Object}
// msg.retry {Number}
// msg.event {String}
console.log(msg);
}));
};
REQUEST(opt);
Source: Medium - Peter Širka
The Tech Platform
Comments