From b4acb9941c065083e9110348dabf79534129196f Mon Sep 17 00:00:00 2001 From: satori Date: Tue, 30 Nov 2021 23:30:46 +0800 Subject: [PATCH] doc --- README.md | 21 ++++++++++++++++++++- index.js | 12 ++++++------ 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 00c6e20..013ecb9 100644 --- a/README.md +++ b/README.md @@ -305,7 +305,9 @@ let socket = new WebSocket("ws://localhost:2333"); socket.onopen = function(e) { alert("[open] Connection established"); alert("Sending to server"); - socket.send("My name is John"); + + // 向 xxxx 频道发送消息, data内的格式由客户端约定 + socket.send({fm:'xxxx', data:"My name is John"}); }; socket.onmessage = function(event) { @@ -329,9 +331,26 @@ socket.onerror = function(error) { +* 注意, 必须要在已经登录的状态下才能成功建立 websocket 连接, 因为消息分发服务是基于订阅模式的 +* 全局只需要使用一个连接, 订阅的频道消息都会通过这个连接传递 +* 当用户(多个终端)建立多个连接时, 每个终端都能收到推送消息 +```javascript +{ + fm: 'xxxxxxx', // 频道 + uid: 'xxxxxx', // 来源用户ID, 如果是系统消息, 此项忽略 + data: {} +} +``` + +* 用户发送的消息, 格式由终端约定, 注意不符合约定的格式应直接丢弃 +* 可应用于聊天室, 系统通知, 实时公告, 协作, 消息盒子 +* 非用户消息时, uid可忽略 +* data为消息主体, 格式不受服务端控制, 可以为字符串,数字,对象,数组 + + #### 对象列表 diff --git a/index.js b/index.js index 60e4914..e98d4f9 100644 --- a/index.js +++ b/index.js @@ -56,10 +56,10 @@ const HUB = class { 取消订阅(fid, uid) { this.频道(fid).filter(item => item != uid) } - 发送消息(fid, data) { - this.频道(fid).forEach(uid => { - this.用户(uid).forEach(ws => { - ws.send({ fm: fid, data }) + 发送消息(fid, uid, data) { + this.频道(fid).forEach(userid => { + this.用户(userid).forEach(ws => { + ws.send({ fm: fid, uid, data }) }) }) } @@ -98,8 +98,8 @@ function websocketer(ws, req) { ws.on('message', function (msg) { // 可能需要检查权限, 是否可以向指定目标发送, 或者由客户端过滤 // 还需要在 data 中附带上发送者信息 - let { fid, data } = msg - FM.发送消息(fid, data) + let { fm, data } = msg + FM.发送消息(fm, req.session.account.uid, data) }) // 关闭连接时