I am getting started with Server Sent Events (SSE) since my web app requires receiving real time updates from the server. It does not require sending anything to the server,
When the stream closes, you need to remove your event listener so you won't try to write to the stream again. That could be done like this:
router.get('/updates', (req, res) => {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
function listener(event) {
console.log('Event triggered! Sending response.');
res.write('data: Event triggered!\n\n');
}
// Listens for 'event' and sends an 'Event triggered!' message to client when its heard.
eventEmitter.addListener('event', listener);
req.on('close', () => {
// remove listener so it won't try to write to this stream any more
eventEmitter.removeListener('event', listener);
console.log('Connection to client closed.');
res.end();
});
});
module.exports = router;
FYI, I don't think you need the res.end()
when you've already received the close
event. You would use res.send()
if you were unilaterally trying to close the connection from the server, but if it's already closing, I don't think you need it and none of the code examples I've seen use it this way.
I wonder if it's possible that your res.end()
is also why you're getting two close
events. Try removing it.