forked from torinmb/Socket-Server-Template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
83 lines (69 loc) · 1.98 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
const http = require("http");
const express = require("express");
const app = express();
app.use(express.static("public"));
// require("dotenv").config();
const serverPort = process.env.PORT || 3000;
const server = http.createServer(app);
const WebSocket = require("ws");
let keepAliveId;
const wss =
process.env.NODE_ENV === "production"
? new WebSocket.Server({ server })
: new WebSocket.Server({ port: 5001 });
server.listen(serverPort);
console.log(`Server started on port ${serverPort} in stage ${process.env.NODE_ENV}`);
wss.on("connection", function (ws, req) {
console.log("Connection Opened");
console.log("Client size: ", wss.clients.size);
if (wss.clients.size === 1) {
console.log("first connection. starting keepalive");
keepServerAlive();
}
ws.on("message", (data) => {
let stringifiedData = data.toString();
if (stringifiedData === 'pong') {
console.log('keepAlive');
return;
}
broadcast(ws, stringifiedData, false);
});
ws.on("close", (data) => {
console.log("closing connection");
if (wss.clients.size === 0) {
console.log("last client disconnected, stopping keepAlive interval");
clearInterval(keepAliveId);
}
});
});
// Implement broadcast function because of ws doesn't have it
const broadcast = (ws, message, includeSelf) => {
if (includeSelf) {
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
} else {
wss.clients.forEach((client) => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
}
};
/**
* Sends a ping message to all connected clients every 50 seconds
*/
const keepServerAlive = () => {
keepAliveId = setInterval(() => {
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send('ping');
}
});
}, 50000);
};
app.get('/', (req, res) => {
res.send('Hello World!');
});