Skip to content

Instantly share code, notes, and snippets.

@rbaulin
Created June 12, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rbaulin/ff20696aaf2077379517 to your computer and use it in GitHub Desktop.
Save rbaulin/ff20696aaf2077379517 to your computer and use it in GitHub Desktop.
var path = require('path');
var express = require('express');
var app = express();
var openConnections = [];
global.emitEvent = function () {
console.log("emit to clients " + openConnections.length);
openConnections.forEach(function(res) {
res.write('data: event' + "\n\n");
});
}
// simple route to register the clients
app.get('/eventstream', function(req, res) {
// set timeout as high as possible
req.socket.setTimeout(0); // 0x7FFFFFFF
res.writeHead(200, {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
res.write('\n');
// push this res object to our global variable
openConnections.push(res);
console.log("event stream new connection");
req.on("close", function() {
var toRemove;
for (var j =0 ; j < openConnections.length ; j++) {
if (openConnections[j] == res) {
toRemove =j;
break;
}
}
openConnections.splice(j,1);
console.log(openConnections.length);
});
});
setInterval(function() {
emitEvent();
}, 1000);
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.html');
});
app.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment