-
Notifications
You must be signed in to change notification settings - Fork 0
/
ws.js
69 lines (49 loc) · 1.51 KB
/
ws.js
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
const ws = require('nodejs-websocket');
const createServer = () => {
let server = ws.createServer(connection => {
connection.on('text', function (res) {
let info = JSON.parse(res);
if (info.all) {
broadcastALL(server, info);
} else {
broadcastSingle(server, info)
}
})
connection.on('connect', function(code) {
console.log('开启连接', code)
})
connection.on('close', function(code) {
console.log('关闭连接', code)
})
connection.on('error', function(code) {
// 某些情况如果客户端多次触发连接关闭,会导致connection.close()出现异常,这里try/catch一下
try {
connection.close()
} catch (error) {
console.log('close异常', error)
}
console.log('异常关闭', code)
})
}).listen(8001);
server.on('close', () => {
// chatUsers = []
});
return server
}
// 通知到所有用户
const broadcastALL= (server, info) => {
server.connections.map((conn) => {
if(conn.path === '/'+info.sid){
conn.sendText(JSON.stringify(info));
}
})
}
// 通知到个人
const broadcastSingle = (server, info) => {
server.connections.map((conn) => {
if(conn.path === '/'+info.sid){
conn.sendText(JSON.stringify(info));
}
})
}
module.exports = createServer;