-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
101 lines (83 loc) · 2.02 KB
/
Copy pathindex.js
File metadata and controls
101 lines (83 loc) · 2.02 KB
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
const { WebSocketServer } = require("ws");
const wss = new WebSocketServer({ port: 3000 });
const maxClients = 2;
let rooms = {};
wss.on('connection', function connection(ws) {
ws.on('message', function message(data) {
const obj = JSON.parse(data);
const type = obj.type;
const params = obj.params;
switch (type) {
case "create":
create(params);
break;
case "join":
join(params);
break;
case "leave":
leave(params);
break;
default:
console.warn(`Type: ${type} unknown`);
break;
}
});
function generalInformation(ws) {
let obj;
if (ws["room"] !== undefined)
obj = {
"type": "info",
"params": {
"room": ws["room"],
"no-clients": rooms[ws["room"]].length,
}
}
else
obj = {
"type": "info",
"params": {
"room": "no room",
}
}
ws.send(JSON.stringify(obj));
}
function create(params) {
const room = genKey(5);
rooms[room] = [ws];
ws["room"] = room;
generalInformation(ws);
}
function genKey(length) {
let result = '';
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * characters.length));
}
return result;
}
function join(params) {
const room = params.code;
if (!Object.keys(rooms).includes(room)) {
console.warn(`Room ${room} does not exist!`);
return;
}
if (rooms[room].length >= maxClients) {
console.warn(`Room ${room} is full!`);
return;
}
rooms[room].push(ws);
ws["room"] = room;
generalInformation(ws);
}
function leave(params) {
const room = ws.room;
rooms[room] = rooms[room].filter(so => so !== ws);
ws["room"] = undefined;
if (rooms[room].length == 0)
close(room);
generalInformation(ws);
}
function close(room) {
rooms = rooms.filter(key => key !== room);
}
});