Skip to content

Instantly share code, notes, and snippets.

@siliskin
Forked from alaingilbert/server.js
Created July 13, 2012 22:38
Show Gist options
  • Save siliskin/3108010 to your computer and use it in GitHub Desktop.
Save siliskin/3108010 to your computer and use it in GitHub Desktop.
EventSource server with nodejs
var http = require('http')
, fs = require('fs')
, PORT = process.argv[2] || 8080
, HOST = process.argv[3] || '127.0.0.1';
http.createServer(function (req, res) {
if (req.url == '/events') {
res.writeHead(200, { 'Content-Type' : 'text/event-stream'
, 'Cache-Control' : 'no-cache'
, 'Connection' : 'keep-alive'
});
console.log('Client connect');
var t = setInterval(function () {
console.log('Send data');
res.write('data: DATA\n\n');
}, 1000);
res.socket.on('close', function () {
console.log('Client leave');
clearInterval(t);
});
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(fs.readFileSync(__dirname + '/templates/index.html'));
res.end()
}
}).listen(PORT, HOST);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment