-
Notifications
You must be signed in to change notification settings - Fork 0
/
broker.js
99 lines (90 loc) · 3.21 KB
/
broker.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
class Broker {
constructor(mgr) {
this.mgr = mgr;
this.players = {};
this.admins = {};
}
AddPlayerSocket(s, gameID) {
console.log('Player joining game', gameID)
this.mgr.Get(gameID)
.then((game) => {
if (!game) {
console.log('Invalid game id', gameID);
// TODO: signal 404 back to user somehow
return;
}
if (!(gameID in this.players)) {
this.players[gameID] = [];
}
this.players[gameID].push(s);
s.on('error', (err) => {
console.log('Player socket error', err);
s.close();
})
s.on('close', () => {
// Remove this socket from the list.
const idx = this.players[gameID].indexOf(s);
this.players[gameID].splice(idx, 1);
})
// Send initial game state.
s.send(JSON.stringify(game));
})
.catch(console.error);
}
AddAdminSocket(s, gameID) {
console.log('Admin joining game', gameID)
this.mgr.Get(gameID)
.then((game) => {
if (!game) {
console.log('Invalid game id', gameID);
// TODO: signal 404 back to user somehow
return;
}
if (!(gameID in this.admins)) {
this.admins[gameID] = [];
}
this.admins[gameID].push(s);
s.on('error', (err) => {
console.log('Admin socket error', err);
s.close();
})
s.on('close', () => {
// Remove this socket from the list.
const idx = this.admins[gameID].indexOf(s);
this.admins[gameID].splice(idx, 1);
})
s.on('message', (msg) => {
try {
const newState = JSON.parse(msg);
this.mgr.Update(gameID, newState)
.then(() => {
this.updateClients(gameID);
})
.catch(console.error);
} catch (err) {
console.error('Update error:', err);
}
});
// Send initial game state.
s.send(JSON.stringify(game));
})
.catch(console.error);
}
updateClients(gameID) {
this.mgr.Get(gameID)
.then((game) => {
if (!game) { return; }
const newState = JSON.stringify(game);
const players = this.players[gameID]
if (players) {
players.map((p) => { p.send(newState); });
}
const admins = this.admins[gameID];
if (admins) {
admins.map((a) => { a.send(newState) })
}
})
.catch(console.error);
}
}
exports.Broker = Broker;