I am using server sent events in MEAN stack. I am able to push data from server to client whenever required.
But one thing i noticed that even if i am the only client hitting the server. There are multiple listeners for me and events are broadcast to say 40 listeners(if i wait long enough for the client to reconnect 40 times).
Multiple listeners are also created when user reloads.
How can i limit the listeners to say 1 listener to per event per client. Is this even possible with server sent events.
I am trying to keep the connection open as long as the user is using the website and close only when the browser/tab is closed or clients request a reload.
NOTE : stream is an EventEmitter object which I use to pass events so that the required changes can be monitored and appropriate data can be send through server sent events.
const function = async (request: Request, response: Response) => {
console.log("client connected to broadcasting channel")
console.log("listeners : " , stream.listenerCount('event-L'))
response.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
"X-Accel-Buffering": "no"
});
response.flushHeaders();
stream.on('event-L', (event, data) => {
console.log("Broadcasting event-L")
response.write('event: ' + event + '\n' + 'data:' + JSON.stringify(data) + '\n\n')
}
})
stream.on('event-U', (event, data) => {
console.log("Broadcasting event-U.")
response.write('event: ' + event + '\n' + 'data:' + JSON.stringify(data) + '\n\n')
}
})
response.on('close', () => {
console.log('client dropped me');
response.end();
})
}