-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwsserver.js
107 lines (91 loc) · 2.76 KB
/
wsserver.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
100
101
102
103
104
105
106
107
// require('dotenv').config();
const WebSocket = require('ws');
const fs = require('fs');
const port = process.env.WSPORT || 3010;
const INIT_COURTS = "INIT_COURTS";
const ADD_COURT = "ADD_COURT";
const UPDATE_COURT = "UPDATE_COURT";
const TEST_CONNECTIONS = "TEST_CONNECTIONS";
// const {SurvivorDraft} = require("./SurvivorDraft.js")
class ScoreboardServer{
constructor()
{
this._WSS = new WebSocket.Server({
port: port,
clientTracking: true,
});
this.__CLIENTS = new Map();
this.__COURTS = {
Court1: {
TeamA:{
Name: "test",
Points: 0
},
TeamB:{
Name: "test",
Points: 0
}
}
};
this._WSS.on('connection', ( ws, req ) => {
let token = req.url.split('/').pop();
var storageToken = this.parseNewToken(token);
this.__CLIENTS.set(storageToken, ws);
ws.send(JSON.stringify({
command: INIT_COURTS,
params: this.__COURTS
}));
ws.on('message', (message) => { // process incoming messages from the websocket.
this.processMessage(message, token, ws);
});
ws.on("close", (code, reason) => {
this.__CLIENTS.delete(token)
})
});
}
parseNewToken(token)
{
var firstBracket = token.indexOf("[");
var lastBracket = token.indexOf("]");
if (this.__CLIENTS.has(token)){
if (firstBracket == -1){
return this.parseNewToken(`${token}[1]`)
} else {
var number = Number.parseInt(token.slice(firstBracket+1,lastBracket));
return this.parseNewToken(`${token.slice(0,-(token.length - firstBracket))}[${number+1}]`)
}
} else {
return token;
}
}
processMessage(message, token, ws)
{
var m = JSON.parse(message);
switch(m.command){
case ADD_COURT:
this.__CHATHISTORY.push(m.params);
this.broadcastMessage(message);
break;
case UPDATE_COURT:
if (this.__DRAFT != null){
this.__DRAFT.selectPlayer(m.params.TeamId,m.params.Player)
}
break;
case TEST_CONNECTIONS:
this.broadcastMessage(message);
break;
}
}
broadcastMessage(message, socket = false)
{
if (typeof(message) === 'object'){
message = JSON.stringify(message)
}
this.__CLIENTS.forEach( (item) => {
if (item.readyState === WebSocket.OPEN /* && item !== socket */){
item.send(message)
}
});
}
}
var WsServer = new ScoreboardServer();