Created
December 12, 2011 12:14
-
-
Save alaingilbert/1466875 to your computer and use it in GitHub Desktop.
EventSource server with nodejs
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 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); |
@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
'Connection' : 'keep-alive' - What for?