Skip to content

Instantly share code, notes, and snippets.

@robertoentringer
Forked from alanhoff/client.js
Last active August 8, 2019 11:55
Show Gist options
  • Save robertoentringer/346939521eb825cc9d2c01f5ad7c376e to your computer and use it in GitHub Desktop.
Save robertoentringer/346939521eb825cc9d2c01f5ad7c376e to your computer and use it in GitHub Desktop.
Exemplo de SSE com Node.js eventSource Server-Sent-Events
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