This repository has been archived by the owner on Aug 9, 2018. It is now read-only.
forked from Litarvan/ClientServer
-
Notifications
You must be signed in to change notification settings - Fork 1
/
GamesNetworkManager.js
80 lines (74 loc) · 2.92 KB
/
GamesNetworkManager.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
var Utility = require('./Utility/Utility');
var CreateFunction = Utility.CreateFunction;
var startedGames = 0;
var toStartGames = 0;
var gameJSONs = [];
var onlineGameServers = [];
function GamesNetworkManager(serverLogic) {
var WebSocketServer = require('ws').Server;
this.connectedWMSP = 0;
this.websocket = new WebSocketServer({ port: 7778 });
this.serverLogic = serverLogic;
this.currentGameServerID = 0;
console.log("Started server on port 7778");
this.websocket.on('connection', CreateFunction(this, function connection(ws) {
this.connectedWMSP++;
ws = ws;
onlineGameServers.push(ws);
ws.on('message', CreateFunction(this, function (messageString) {
var message = null;
console.log("Got message: " + messageString);
try {
message = JSON.parse(messageString);
} catch (err) {
console.log("JSON Parsing error: " + messageString);
return;
}
var messageTitle = message['message'];
switch (messageTitle) {
case "Key": {
console.log("key received")
ws.key = message['key'];
} break;
case "PortToUse": {
GamesNetworkManager.prototype.startGame.call(this, message['port'], message['lobbyID'], message['ip'])
} break;
case "SureICan": {
if (ws.key == "abcdefg123") {
if (toStartGames > startedGames) {
GamesNetworkManager.prototype.sendToPlayer.call(this, ws, { message: 'StartGame', gameJSON: gameJSONs[startedGames], lobbyID: message['lobbyID'] })
startedGames++;
}
}
}
}
}))
ws.on('close', CreateFunction(this, () => {
this.connectedWMSP--;
console.log("GameHost disconnected")
onlineGameServers.splice(onlineGameServers.indexOf(ws), 1);
}));
}))
}
GamesNetworkManager.prototype.startGame = function (port, lobbyID, ip) {
this.serverLogic.lobbyManager.startGame(port, lobbyID, ip)
}
GamesNetworkManager.prototype.orderGameStart = function (gameJSON, lobbyID) {
toStartGames++;
gameJSONs.push(gameJSON)
this.sendToAll({ message: 'CouldYouStart', lobbyID });
}
var OPEN_STATE = require('ws').OPEN;
GamesNetworkManager.prototype.sendToAll = function (object) {
var sendString = JSON.stringify(object);
for (var i = 0; i < onlineGameServers.length; i++) {
var player = onlineGameServers[i];
if (player.readyState !== OPEN_STATE) continue;
player.send(sendString);
}
}
GamesNetworkManager.prototype.sendToPlayer = function (player, object) {
if (player.readyState !== OPEN_STATE) return;
player.send(JSON.stringify(object));
};
module.exports = GamesNetworkManager;