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
|
const WebSocket = require("ws");
function startServer() {
const server = new WebSocket.Server({ port: 8080 });
const connections = new Array();
let maxID = 0;
console.log("Websocket server is running on port 8080.");
server.on("connection", (socket, request) => {
const userName = request.url.substring(11);
maxID++;
const current_connection = {
userName: userName,
id: maxID,
socket: socket,
};
socket.on("message", (data) => {
console.log("[" + current_connection.id + "] " + data);
});
socket.on("close", (code, reason) => {
console.log(
"[" +
current_connection.id +
"] Disconnected: [" +
code +
"] " +
reason,
);
if (code !== 1008) {
for (const conn of connections) {
if (conn.id !== current_connection.id) {
conn.socket.send(userName + " disconnected");
}
}
connections.splice(connections.indexOf(current_connection), 1);
}
});
for (const conn of connections) {
if (conn.userName === userName) {
socket.close(
1008,
'Username: "' + userName + '" is already taken',
);
return;
}
}
socket.send("Welcome " + userName);
connections.push(current_connection);
if (connections.length === 1) {
socket.send(userName + ", you are the only player connected");
} else {
socket.send(connections.length + " players are connected");
}
for (const conn of connections) {
if (conn.userName !== userName) {
conn.socket.send(userName + " connected");
}
}
if (connections.length < 4) {
for (const conn of connections) {
conn.socket.send(
"Waiting for " +
(4 - connections.length) +
" other players to start the game",
);
}
} else {
for (const conn of connections) {
conn.socket.send(
"Match will start soon, disconnecting " +
conn.userName +
" from the lobby",
);
conn.socket.close(1000, "Match is starting");
}
}
});
return server;
}
module.exports = {
startServer,
};
|