/
index.js
43 lines (37 loc) · 1 KB
/
index.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
const {OPEN, Server} = require('ws')
const wss = new Server({port: 3714})
const channels = {}
const channelUsers = {}
wss.on('connection', (ws, request) => {
let channel
const handlers = {
channel (next) {
channel = next
channels[channel] = channels[channel] || {}
channelUsers[channel] = channelUsers[channel] || []
channelUsers[channel].push(ws)
ws.send(JSON.stringify({
type: 'positions',
positions: channels[channel]
}))
},
position (id, x, y, z) {
channels[channel][id] = {x, y, z}
channelUsers[channel].forEach(user => {
if (user.readyState !== OPEN) {
channelUsers[channel] = channelUsers[channel].filter(user =>
user.readyState === OPEN
)
}
user.send(JSON.stringify({
type: 'position',
position: [id, x, y, z]
}))
})
}
}
ws.on('message', message => {
const [type, ...data] = JSON.parse(message)
handlers[type](...data)
})
})