From bf48417e516f5b1a94331c219e18e5b5289e60b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A7=89?= Date: Thu, 16 May 2024 19:51:59 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0vite=20=E4=BD=BF=E7=94=A8=20S?= =?UTF-8?q?SE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- index.js | 40 ++++++++++++++++++++++++++++++++++++++++ package.json | 3 ++- 2 files changed, 42 insertions(+), 1 deletion(-) 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(` +

SSE Express

+ + `) +}) + app.use(express.json()) app.use(express.urlencoded({ extended: false })) app.use(session({ secret: 'kana', name: 'sid', resave: false, saveUninitialized: false, cookie: { maxAge: 180 * 24 * 3600000 }, store: session_store })) diff --git a/package.json b/package.json index 69846e4..ed308a6 100644 --- a/package.json +++ b/package.json @@ -25,6 +25,7 @@ "start": "node index.js" }, "devDependencies": { - "nodemon": "^3.1.0" + "nodemon": "^3.1.0", + "vite": "^5.2.11" } }