Files
test_dashboard/server/sse.js
T

40 lines
872 B
JavaScript
Raw Normal View History

2026-05-20 11:52:18 -04:00
'use strict';
const clients = new Set();
/**
* Register an SSE response and keep the connection alive.
*/
function addClient(res) {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.flushHeaders();
// Send an immediate heartbeat so the browser knows the stream is live
res.write('data: {"type":"connected"}\n\n');
const heartbeat = setInterval(() => {
res.write(': heartbeat\n\n');
}, 20000);
clients.add(res);
res.on('close', () => {
clearInterval(heartbeat);
clients.delete(res);
});
}
/**
* Push an event to all connected SSE clients.
*/
function broadcast(data) {
const payload = `data: ${JSON.stringify(data)}\n\n`;
for (const client of clients) {
client.write(payload);
}
}
module.exports = { addClient, broadcast };