-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
69 lines (57 loc) · 1.82 KB
/
index.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
"use strict";
const express = require("express");
const WebSocket = require("ws");
const PORT = process.env.PORT || 3000;
const INDEX = "/frontend/views/index.html";
require('events').EventEmitter.prototype._maxListeners = 35;
const server = express()
.use(express.static("frontend"))
.use((req, res) => res.sendFile(INDEX, { root: __dirname }))
.listen(PORT, () => console.log(`Listening on ${PORT}`));
const wss = new WebSocket.Server({ server });
let answerOrder = [];
wss.on("connection", (socketClient) => {
try {
console.log("New connection. Number of clients: ", wss.clients.size);
socketClient.send(JSON.stringify({ answerOrder }));
} catch (err) {
console.log(err);
}
socketClient.on("message", (message) => {
try {
const messageString = message.toString();
const messageJSON = JSON.parse(messageString);
if (messageJSON.answerer) {
answerOrder.push({teamName: messageJSON.answerer, answer: messageJSON.answer});
}
if (messageJSON.reset) {
answerOrder = [];
}
wss.clients.forEach((client) => {
try {
if (client.readyState === WebSocket.OPEN) {
if (messageJSON.answerer || messageJSON.reset) {
client.send(JSON.stringify({ answerOrder }));
}
if (messageJSON.reset) {
client.send(JSON.stringify({ answerOrder, reset: true }));
}
}
} catch (err) {
console.log(err);
}
});
} catch (err) {
console.log(err);
}
socketClient.on("close", (socketClient) => {
console.log("closed");
console.log("Number of clients: ", wss.clients.size);
});
});
});
setInterval(() => {
wss.clients.forEach((client) => {
client.send(JSON.stringify({ date: new Date().toTimeString() }));
});
}, 1000);