-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
67 lines (55 loc) · 1.84 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
const WebSocket = require("ws");
const winston = require("winston");
const logConfiguration = {
transports: [new winston.transports.Console()],
};
function noop() {}
function heartbeat() {
this.isAlive = true;
}
const logger = new winston.createLogger(logConfiguration);
const PORT = process.env.PORT || 8090;
const wss = new WebSocket.Server({ port: PORT });
logger.info(`Started websocket server on port: ${PORT}`);
wss.on("connection", function connection(ws, req) {
const ip = req.socket.remoteAddress;
logger.info(`new client connected: ${ip}`);
// set up alive check to terminate if client does not pong back
ws.isAlive = true;
ws.on("pong", heartbeat);
ws.on("message", function incoming(data) {
logger.info(`logger, incoming data: ${data}`);
// Broadcast to everyone else.
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
logger.info(
`logger, Broadcasting message to ${wss.clients.size - 1} clients`
);
client.send(data);
}
});
});
ws.on("close", function (code, reason) {
console.log("connection closed by remote");
console.log(`this._socket.remoteAddress: ${this._socket.remoteAddress}`);
console.log(`code: ${code}`);
console.log(`reason: ${reason}`);
});
});
const interval = setInterval(function ping() {
wss.clients.forEach(function each(ws) {
logger.info(`checking if client is still alive`);
logger.info(JSON.stringify(ws._socket.address()));
if (ws.isAlive === false) {
logger.info("logger, connection no longer alive, terminating");
return ws.terminate();
}
ws.isAlive = false;
ws.ping(noop);
logger.info("client is still alive.");
});
}, 30000);
wss.on("close", function close() {
logger.info(`connection closed`);
clearInterval(interval);
});