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