# 统计聊天人数
服务端:
ws.on('message', function (msg) {
var msgObj = JSON.parse(msg)
if (msgObj.name) {
ws.name = msgObj.name
}
// 广播到其他的客户端
wss.clients.forEach(function each(client) {
msgObj.num = wss.clients.size
// 广播给非自己的其他客户端
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(msgObj));
}
});
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
统计聊天人数:
- 服务端把在线的clients数量返回给客户端
- 客户端接收消息(包括自己)
# 多个聊天室
- 存储聊天室(会话)
- 内存中进行存储
- redis
- redis + mongoDB
- localstorage + 重连机制
- 指定发送消息
- 统计在线人数
var group = {}
// ...
// console.log('a new client is connected!');
ws.on('message', function (msg) {
var msgObj = JSON.parse(msg)
if (msgObj.name) {
ws.name = msgObj.name
}
if (typeof ws.roomid === 'undefined' && msgObj.roomid) {
ws.roomid = msgObj.roomid
if (typeof group[ws.roomid] === 'undefined') {
group[ws.roomid] = 1
} else {
group[ws.roomid]++
}
}
// 广播到其他的客户端
wss.clients.forEach(function each(client) {
msgObj.num = group[ws.roomid]
if (client.readyState === WebSocket.OPEN && client.roomid === ws.roomid) {
client.send(JSON.stringify(msgObj));
}
// msgObj.num = wss.clients.size
// // 广播给非自己的其他客户端
// if (client.readyState === WebSocket.OPEN) {
// client.send(JSON.stringify(msgObj));
// }
});
})
// ...
// 客户端断开链接
ws.on('close', function () {
// console.log('one client is closed :' + ws);
if (typeof ws.name !== 'undefined') {
// 退出的用户,修改对应的在线客户端数据
group[ws.roomid]--
// 广播到其他的客户端
wss.clients.forEach(function each(client) {
// 广播给非自己的其他客户端
if (client !== ws && ws.roomid === client.roomid && client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({
name: ws.name,
event: 'logout',
num: group[ws.roomid]
}));
}
});
}
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53