From 3fbc863e1513b2b65a928653dd5d30254f2abfd3 Mon Sep 17 00:00:00 2001 From: satori Date: Sat, 4 Dec 2021 04:57:06 +0800 Subject: [PATCH] =?UTF-8?q?=E5=85=81=E8=AE=B8=E6=B8=B8=E5=AE=A2ws=E8=BF=9E?= =?UTF-8?q?=E6=8E=A5=E5=88=B0=E5=85=AC=E5=85=B1=E9=A2=91=E9=81=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 10 ++++++++++ index.js | 15 +++++++++------ 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 013ecb9..7fa07d6 100644 --- a/README.md +++ b/README.md @@ -352,6 +352,16 @@ socket.onerror = function(error) { +#### 游客广播 + +允许未登录会话加入订阅, 将未登录会话加入到游客账户 + +因此不能再通过账户登录状态进行拦截 + + + + + #### 对象列表 `GET` /:name diff --git a/index.js b/index.js index 14098a3..4d400b5 100644 --- a/index.js +++ b/index.js @@ -82,15 +82,18 @@ const FM = new HUB() function websocketer(ws, req) { // 验证身份已经登录 - if (!req.session.account) return ws.close() + //if (!req.session.account) return ws.close() + + // 游客使用公共账户 uid = 0 + let uid = req.session?.account?.uid || 0 // 将连接加入到列表 - FM.增加会话(req.session.account.uid, ws) + FM.增加会话(uid, ws) // 当用户连接时, 读取其订阅列表 - db('user').findOne({ uid: req.session.account.uid }, function (err, doc) { + db('user').findOne({ uid }, function (err, doc) { if (doc && Array.isArray(doc.fm)) { - doc.fm.forEach(fid => FM.订阅频道(fid, req.session.account.uid)) + doc.fm.forEach(fid => FM.订阅频道(fid, uid)) } }) @@ -99,12 +102,12 @@ function websocketer(ws, req) { // 可能需要检查权限, 是否可以向指定目标发送, 或者由客户端过滤 // 还需要在 data 中附带上发送者信息 let { fm, data } = msg - FM.发送消息(fm, req.session.account.uid, data) + FM.发送消息(fm, uid, data) }) // 关闭连接时 ws.on('close', function (code) { - FM.移除会话(req.session.account.uid, ws) + FM.移除会话(uid, ws) }) // 发生错误时