-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocket.js
More file actions
36 lines (28 loc) · 885 Bytes
/
socket.js
File metadata and controls
36 lines (28 loc) · 885 Bytes
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
const webSocket = require('ws')
let sockets=[]
module.exports = (server)=>{
const wss = new webSocket.Server({server})
wss.on('connection',(ws,req)=>{
ws.id = req.headers['sec-websocket-key']
sockets.push(ws)
console.log(req.connection.remoteAddress)
ws.on('close',(code,reason)=>{
console.log('Off')
sockets = sockets.filter(v=>{
return ws.id !== v.id
})
console.log(sockets.length)
})
ws.on('message',(response)=>{
let obj = JSON.parse(response.toString('utf-8'))
let {type,data}=obj
switch(type){
case 'send_msg':
sockets.forEach(v=>{
v.send(JSON.stringify(data))
})
break;
}
})
})
}