-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathapp.js
50 lines (44 loc) · 1.4 KB
/
app.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
const WebSocket = require('ws')
// create new websocket server
const wss = new WebSocket.Server({port: 8000})
// empty object to store all players
var players = {}
// add general WebSocket error handler
wss.on('error', function error (error) {
console.error('WebSocket error', error)
})
// on new client connect
wss.on('connection', function connection (client) {
console.log('new client connected')
// on new message recieved
client.on('message', function incoming (data) {
// get data from string
var [udid, x, y, z] = data.toString().split('\t')
// store data to players object
players[udid] = {
position: {
x: parseFloat(x),
y: parseFloat(y) + 1,
z: parseFloat(z)
},
timestamp: Date.now()
}
// save player udid to the client
client.udid = udid
})
})
function broadcastUpdate () {
// broadcast messages to all clients
wss.clients.forEach(function each (client) {
// filter disconnected clients
if (client.readyState !== WebSocket.OPEN) return
// filter out current player by client.udid
var otherPlayers = Object.keys(players).filter(udid => udid !== client.udid)
// create array from the rest
var otherPlayersPositions = otherPlayers.map(udid => players[udid])
// send it
client.send(JSON.stringify({players: otherPlayersPositions}))
})
}
// call broadcastUpdate every 0.1s
setInterval(broadcastUpdate, 100)