diff --git a/index.js b/index.js index 16097e9..356080c 100644 --- a/index.js +++ b/index.js @@ -406,6 +406,46 @@ function index_get(req, res) { } const app = expressWs(express()).app +const ServerSentEventsClient = {} + +// Server-Sent Events (发送版本号来决定是否接收更新?) +app.use((req, res, next) => { + if (req.get('Accept') === 'text/event-stream') { + console.log('SSE 连接', req.path) + res.set({ + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache', + 'Connection': 'keep-alive' + }) + res.write('retry: 10000\n\n') + res.write(`data: ${JSON.stringify({ fm: 'message', data: 'hello' })}\n\n`) + res.write(`data: ${JSON.stringify({ fm: 'message', data: 'hellox' })}\n\n`) + if (!ServerSentEventsClient[req.path]) ServerSentEventsClient[req.path] = [] + ServerSentEventsClient[req.path].push({ req, res }) + req.on('close', () => { + console.log('SSE 断开', req.path) + let index = ServerSentEventsClient[req.path].findIndex(item => item.res === res) + if (index !== -1) ServerSentEventsClient[req.path].splice(index, 1) + }) + } else { + next() + } +}) + +// SEE DEMO +app.route('/demo').get((req, res) => { + res.send(` +