Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Exemplo de SSE com Node.js
var source = new EventSource('http://localhost:8080');
source.addEventListener('message', function(data){
console.log(data);
});
source.addEventListener('open', function(){
console.log('Conexão aberta!');
});
source.addEventListener('error', function(err){
console.log(err.stack);
});
require('http').Server(function(req, res){
console.log(req.method);
// Setamos as headers para indicar um SSE e evitar cache
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Access-Control-Allow-Origin': '*',
'Connection': 'keep-alive'
});
// Iniciamos o envio da hora atual a cada segundo
var timer = setInterval(function(){
res.write('data:' + JSON.stringify({
date: new Date()
}) + '\n\n'); // Não esquecer o EOL duplo
}, 1000);
// Caso a conexão caia/pare/feche, precisamos parar o timer
req.on('close', function(){
clearInterval(timer);
});
}).listen(8080, '0.0.0.0');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.