-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
218 lines (194 loc) · 6.56 KB
/
main.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
const fs = require("fs");
const { WebSocketServer } = require("ws");
const http = require("http");
const { randomUUID } = require("crypto");
const port = process.env.PORT || 3000;
const server = http.createServer((req, res) => {
switch (req.url) {
case "/":
res.writeHead(200, { "Content-Type": "text/html" });
fs.readFile("./index.html", (err, content) => {
if (err) throw err;
res.write(content);
res.end();
});
break;
case "/script.js":
res.writeHead(200, { "Content-Type": "text/javascript" });
fs.readFile("./script.js", (err, content) => {
if (err) throw err;
res.write(content);
res.end();
});
break;
case "/style.css":
res.writeHead(200, { "Content-Type": "text/css" });
fs.readFile("./style.css", (err, content) => {
if (err) throw err;
res.write(content);
res.end();
});
break;
default:
res.writeHead(404);
res.write("Unkown route");
res.end();
}
});
const wss = new WebSocketServer({ server: server });
let connections = {};
let pairs = {};
let randomWanting = [];
let usernames = {};
wss.on("connection", (conn) => {
// Record new connection
const clientId = randomUUID();
connections[clientId] = conn;
sendData(
{
type: "connection",
clientId: clientId,
},
conn,
);
logData();
conn.on("error", console.error);
conn.on("close", () => {
console.log(`${clientId} has disconnected`);
const opponentId = pairs[clientId];
connections[opponentId] &&
sendData(
{
type: "unpair",
opponentId: opponentId,
},
connections[opponentId],
);
delete connections[clientId];
delete usernames[clientId];
delete usernames[opponentId];
delete pairs[opponentId];
delete pairs[clientId];
randomWanting = randomWanting.filter((id) => id !== clientId);
logData();
});
conn.on("message", (message) => {
message = message.toString();
const data = JSON.parse(message);
console.log(`Message from ${clientId.substring(0, 5)}:`, data);
switch (data.type) {
// First request for creating custom connection
// User just provides username in this request
case "prepareCustomConnection":
randomWanting = randomWanting.filter((id) => id !== clientId);
if (!data.username)
console.error(
"Username not provided for custom connection",
);
usernames[clientId] = data.username;
break;
// Second request for custom connection
// Clients provides id of opponent to connect with
case "connectViaOpponentId":
randomWanting = randomWanting.filter((id) => id !== clientId);
if (
data.opponentId === clientId ||
!connections[data.opponentId]
) {
console.error(
`Invalid connect request: ${clientId} with ${data.opponentId}`,
);
sendData({ type: "pairError" }, conn);
return;
}
pairWith(data.opponentId);
logData();
break;
// Requested to find a random opponent
case "connectRandomly":
usernames[clientId] = data.username;
if (randomWanting.length > 0) {
pairWith(randomWanting.shift());
} else {
randomWanting.push(clientId);
}
logData();
break;
// End of game
case "gameEnd":
sendData({ type: "gameEnd" }, conn);
connections[pairs[clientId]] &&
sendData({ type: "gameEnd" }, connections[pairs[clientId]]);
break;
// Making a move
case "move":
const opponentId = pairs[clientId];
sendData(
{
type: "move",
row: data.row,
col: data.col,
},
conn,
);
connections[opponentId] &&
sendData(
{
type: "move",
row: data.row,
col: data.col,
},
connections[opponentId],
);
break;
default:
console.error("Invalid communcation type");
}
});
function pairWith(opponentId) {
console.log(`Pairing ${clientId} and ${opponentId}`);
pairs[clientId] = opponentId;
pairs[opponentId] = clientId;
const firstPlayer = clientId > opponentId ? clientId : opponentId;
// Notify client after pairing
sendData(
{
type: "pairSuccess",
opponentId: opponentId,
opponentName: usernames[opponentId],
first: firstPlayer,
},
conn,
);
// Also notify opponent after pairing
sendData(
{
type: "pairSuccess",
opponentId: clientId,
opponentName: usernames[clientId],
first: firstPlayer,
},
connections[opponentId],
);
}
});
// Sends data in form of stringified JSON
function sendData(data, connection) {
try {
if (typeof data !== "object")
throw Error("Can only send type 'object'");
if (!connection) throw Error("Connection is invalid");
const jsonData = JSON.stringify(data);
connection.send(jsonData);
} catch (err) {
console.error(err);
console.log(`Provided data: ${data}`);
}
}
function logData() {
console.log("Players:", Object.keys(connections));
console.log("RandomWanting:", randomWanting);
console.log("Pairs:", pairs);
}
const host = "0.0.0.0"
server.listen(port, host, () => console.log(`Listening on ${host}:${port}...`));