Skip to content

Instantly share code, notes, and snippets.

@alaingilbert
Created December 12, 2011 12:14
Show Gist options
  • Save alaingilbert/1466875 to your computer and use it in GitHub Desktop.
Save alaingilbert/1466875 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);
@abdulhannanali
Copy link

@Yaffle You need to keep the connection alive in order to receive the events, that's the whole point of EventSource

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment