Created
June 12, 2015 14:09
-
-
Save rbaulin/ff20696aaf2077379517 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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