forked from kontur-web-courses/place
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.mjs
More file actions
92 lines (74 loc) · 1.95 KB
/
server.mjs
File metadata and controls
92 lines (74 loc) · 1.95 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
import * as path from "path";
import express from "express";
import WebSocket from "ws";
const port = process.env.PORT || 5000;
const apiKeys = new Set([
"4a83051d-aad4-483e-8fc8-693273d15dc7",
"c08c9038-693d-4669-98cd-9f0dd5ef06bf",
"4b1545c4-4a70-4727-9ea1-152ed4c84ae2",
"4a226908-aa3e-4a34-a57d-1f3d1f6cba84",
]);
const colors = [
"#140c1c",
"#442434",
"#30346d",
"#4e4a4e",
"#854c30",
"#346524",
"#d04648",
"#757161",
"#597dce",
"#d27d2c",
"#8595a1",
"#6daa2c",
"#d2aa99",
"#6dc2ca",
"#dad45e",
"#deeed6",
];
const size = 256;
// place(x, y) := place[x + y * size]
const place = Array(size * size).fill(null);
for (const [colorIndex, colorValue] of colors.entries()) {
for (let dx = 0; dx < size; dx++) {
place[dx + colorIndex * size] = colorValue;
}
}
const app = express();
app.use(express.static(path.join(process.cwd(), "client")));
app.get('/api/colors',(_,res)=>{
res.send(colors);
});
app.get("/*", (_, res) => {
res.send("Place(holder)");
});
const server = app.listen(port);
const wss = new WebSocket.Server({
noServer: true,
});
wss.on("connection", function connection(ws) {
ws.on("message", function incoming(message) {
console.log("received: %s", message);
const data = JSON.parse(message).payload;
place[data.x + data.y * size] = data.color;
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({type: 'place',
payload: place,}));
};
});
});
ws.send(JSON.stringify({type: 'place',
payload: place,}));
});
server.on("upgrade", (req, socket, head) => {
const url = new URL(req.url, req.headers.origin);
let apiKey = url.searchParams.get('apiKey');
console.log(url, apiKey);
if(apiKeys.has(apiKey)) {
wss.handleUpgrade(req, socket, head, (ws) => {
wss.emit("connection", ws, req);
});} else {
socket.destroy()
}
});