-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
85 lines (70 loc) · 2.03 KB
/
server.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
const WebSocket = require("ws");
const jwt = require("jsonwebtoken");
function getRandomIntInclusive(min, max) {
const minCeiled = Math.ceil(min);
const maxFloored = Math.floor(max);
return Math.floor(Math.random() * (maxFloored - minCeiled + 1) + minCeiled); // The maximum is inclusive and the minimum is inclusive
}
var globalCount = 0;
function joinGame(myid) {
return function() {
if (globalCount > 75) return;
const userId = myid || getRandomIntInclusive(1, 100000);
console.log("userId", userId);
const ws = new WebSocket("wss://staging.question.house/ws", {
headers: {},
});
ws.userId = userId;
ws.on("error", function (e) {
globalCount--;
clearInterval(ws.pInterval);
console.log("socket error", e);
setTimeout(joinGame(ws.userId), 1000);
});
ws.on("close", function (ree) {
globalCount--;
clearInterval(ws.pInterval);
console.log("socket close", ree);
setTimeout(joinGame(ws.userId), 1000);
});
ws.on("open", function open() {
globalCount++;
ws.pInterval = setInterval(() => {
e.ping()
}, 4000);
ws.send(
JSON.stringify({
type: "subscribe",
})
);
console.log("Connected");
});
ws.on("message", function message(data) {
try {
var message = JSON.parse(data);
} catch (e) {
console.log(data);
}
if (!["question", "questionClosed", "questionResult", "questionSummary", "questionFinished", "dynamicPot", "interaction", "gameStatus", "broadcastStats", "submittedAnswer", "winners", "postGame"].includes(message.type)) console.log(message);
if (message.type == "question") {
ws.send(
JSON.stringify({
type: "answer",
answerId: message.answers[Math.floor(Math.random() * message.answers.length)].answerId,
})
);
}
//console.log('received: %s', data);
});
}
}
setInterval(() => {
joinGame()();
}, 1000);
var http = require("http");
http
.createServer(function (req, res) {
res.write("Hello World!");
res.end();
})
.listen(8080);