Created
August 19, 2013 20:40
-
-
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.
This file contains hidden or 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 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