-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomms.js
More file actions
35 lines (25 loc) · 1007 Bytes
/
comms.js
File metadata and controls
35 lines (25 loc) · 1007 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
var WebSocketServer = require("ws").Server;
module.exports = function Comms(server, engine) {
var nextConnectionId = 0;
var wss = new WebSocketServer({server: server});
wss.on("connection", function (ws) {
ws.id = "player "+(nextConnectionId++);
console.log("websocket connection "+ws.id+" open");
engine.addPlayer(ws.id);
engine.on("gameStateUpdated", sendGameState);
ws.on("close", function () {
engine.removePlayer(ws.id);
engine.removeListener('gameStateUpdated', sendGameState);
console.log("websocket connection "+ws.id+" closed");
});
ws.on('message', function incoming(message) {
var clientState = JSON.parse(message);
engine.updateClientState(clientState, ws.id);
});
function sendGameState() {
deltaString = engine.createMyStateDeltaString(ws.id);
ws.send(deltaString, function () {
});
}
});
};