Skip to content

Instantly share code, notes, and snippets.

@dlindahl
Created August 19, 2013 20:40
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 dlindahl/6273889 to your computer and use it in GitHub Desktop.
Save dlindahl/6273889 to your computer and use it in GitHub Desktop.
Simple Server-Sent Event example that somehow prevents the NodeJS process from handling more than 6 open connections.
var fs = require('fs'),
http = require('http'),
port = process.argv[2] || process.env.PORT || 3000;
http.createServer(function (req, res) {
console.log('REQ:', req.url);
if(req.url == '/') {
console.log('RENDER');
res.write('<html><body>Load the Console</body><script src="/stream.js"></script>');
res.end();
} else if(req.url.match(/\/stream/)) {
console.log('JS');
res.writeHead(200, {
'Content-Type' : 'application/javascript'
});
res.write("console.log('Waiting for ping...');\n"+
"var sse = new EventSource('/firehose');\n"+
"sse.addEventListener('message', function(e) {\n"+
" console.log('PING',e.data);\n"+
"},false);");
res.end();
} else if(req.url.match(/\/firehose/)) {
res.writeHead(200, {
'Content-Type' : 'text/event-stream',
'Cache-Control' : 'no-cache',
'Connection' : 'keep-alive',
'Access-Control-Allow-Origin' : '*'
});
res.write('KEEP ALIVE');
var pinger = setInterval(function() {
res.write('data:'+(+new Date)+'\n\n');
},1000);
res.on('close', function() {
console.log('CLOSED');
clearInterval(pinger);
});
} else {
res.writeHead(404, {});
res.end('Not Found');
}
}).listen(port);
console.log('Server running at port '+port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment