Last active
October 19, 2024 20:53
-
-
Save alanhoff/889b2c96b44debbfad17 to your computer and use it in GitHub Desktop.
Exemplo de SSE com Node.js
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 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); | |
}); |
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
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