57 lines
1.2 KiB
JavaScript
57 lines
1.2 KiB
JavaScript
const express = require('express');
|
|
const router = express.Router();
|
|
|
|
// List of connected SSE clients
|
|
let clients = [];
|
|
|
|
router.get('/stream', (req, res) => {
|
|
res.writeHead(200, {
|
|
'Content-Type': 'text/event-stream',
|
|
'Cache-Control': 'no-cache',
|
|
'Connection': 'keep-alive'
|
|
});
|
|
|
|
const clientId = Date.now() + '-' + Math.random().toString(36).substring(2, 7);
|
|
const newClient = {
|
|
id: clientId,
|
|
res
|
|
};
|
|
clients.push(newClient);
|
|
|
|
// Send initial connection event
|
|
res.write(`data: ${JSON.stringify({ type: 'connected', clientId })}\n\n`);
|
|
|
|
req.on('close', () => {
|
|
clients = clients.filter(c => c.id !== clientId);
|
|
});
|
|
});
|
|
|
|
// 定时发送心跳保持 SSE 长连接活跃,防止代理与浏览器切断
|
|
const sseHeartbeat = setInterval(() => {
|
|
clients.forEach(client => {
|
|
try {
|
|
client.res.write(': ping\n\n');
|
|
} catch (e) {}
|
|
});
|
|
}, 20000);
|
|
if (sseHeartbeat.unref) {
|
|
sseHeartbeat.unref();
|
|
}
|
|
|
|
|
|
function broadcastEvent(eventData) {
|
|
const dataString = `data: ${JSON.stringify(eventData)}\n\n`;
|
|
clients.forEach(client => {
|
|
try {
|
|
client.res.write(dataString);
|
|
} catch (e) {
|
|
// client might have disconnected
|
|
}
|
|
});
|
|
}
|
|
|
|
module.exports = {
|
|
router,
|
|
broadcastEvent
|
|
};
|