I am trying to set up SSE between a NodeJS Server and a TypeScript Frontend. My Server-code looks as following:
let sseInterval: { [index: string]: NodeJS.Timer } = {};
this.app.get('/events/:id', (req, res) => {
const headers = {
'Content-Type': 'text/event-stream',
'Connection': 'keep-alive',
'Cache-Control': 'no-cache'
};
res.writeHead(200, headers);
const instanceId = req.params.id;
const instance = this.findInstance(instanceId);
if (!instance) {
global.logger.debug('sse closed', {metadata: {for: instanceId}})
clearInterval(sseInterval[instanceId]);
res.end();
return;
}
global.logger.debug('sse connected', {metadata: {for: instanceId, instance: instance.config()}})
res.write(`data: ${JSON.stringify(instance.all())}nn`);
sseInterval[instanceId] = setInterval(() => {
global.logger.debug('sse interval', {metadata: {for: instanceId}})
res.write(`data: ${JSON.stringify(instance.all())}nn`);
}, 1000);
req.on('close', () => {
clearInterval(sseInterval[instanceId]);
res.end();
});
});
For the frontend, i am using the following code:
const datapolling = () => {
let eventSource: EventSource = new EventSource(window.server.url + '/events/' + window.server.key);
eventSource.onopen = (event) => {
console.log('connected', event);
}
eventSource.onmessage = (event) => {
console.log('onmessage', new Date(), event);
const json = JSON.parse(event.data);
updateGUI(json);
};
eventSource.onerror = (event) => {
console.error('error', event);
setTimeout(datapolling, 500);
};
window.addEventListener('beforeunload', () => {
eventSource.close();
});
}
console.log('polling', new Date());
datapolling();
The problem is, that the frontend only receives the evenets every 3000ms but 3-4 at once. If i set the backend intervall to 500ms, i get the frontend events every 1500ms, again 3-4 at once.
Is there anything obvious i am doing wrong?