an intro
A communication protocol that works on top of HTTP
and also a JavaScript API
( standardised as part of HTML5 )
that provides a way to push notifications from server to client
without the client's involvement
The usual suspects:
// Subscribe for events on event source of given URL
var eventSource = new EventSource("http://some.service.com/event-source/");
// Subscribe for events on event source of given URL
var eventSource = new EventSource("http://some.service.com/event-source/");
// And then listen for events of specific type
eventSource.addEventListener("progress", function (event) {
var eventData = JSON.parse(event.data);
window.alert('Progress is currently at ' + eventData.currentProgress + '%');
});
// Subscribe for events on event source of given URL
var eventSource = new EventSource("http://some.service.com/event-source/");
// And then listen for events of specific type
eventSource.addEventListener("progress", function (event) {
var eventData = JSON.parse(event.data);
window.alert('Progress is currently at ' + eventData.currentProgress + '%');
});
// When you're done
eventSource.close();
// Listen for errors
eventSource.addEventListener('error', function (event) {
if (event.readyState === EventSource.CLOSED) {
console.log('Connection was closed');
return;
}
console.log('OMG unexpected error occurred. Here\'s some info: ', event);
});
// Listen for notifications that the SSE connection has been established
eventSource.addEventListener('open', function (event) {
console.log('Connection was opened, here come the tasty events');
});
// In this Node.js example, we receive an HTTP request
// (e.g. on http://some.service.com/event-source/)
// so we're given a response object 'res' to write onto
// 1) We write necessary-ish HTTP headers onto the response
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
// 2) Then we write an event (= simply text) onto the response
res.write('event:progress\n');
res.write('data:' + JSON.stringify({ currentProgress: 15 }) + '\n\n');
// To send a second progress event, we simply repeat
res.write('event:progress\n');
res.write('data:' + JSON.stringify({ percentage: 20 }) + '\n\n');
// To send a ping event every second
var id = 0;
setInterval(function () {
++id;
res.write('id:' + id + '\n');
res.write('event:ping\n');
res.write('data:Still here bro\n\n');
}, 1000);
// We never
res.end();
Here's a PHP implementation, if you're interested.
Yes, but they're more complex than you need.*
Websockets allow bi-directional communication, at a price:
Yes, but it's so much worse than the real thing.
*Actually the very first Comet implementations date back to 2000