-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdev-server.js
57 lines (44 loc) · 1.23 KB
/
dev-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
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server, path: '/hereIsWS' });
function handleJsonMessage(ws, json) {
if (!json.type || json.type !== 'control') {
throw Error('Unknown type');
}
const data = json.data;
wss.clients.forEach((client) => client.send(data));
}
function handleMessage(ws, message) {
try {
const json = JSON.parse(message);
handleJsonMessage(ws, json);
} catch {
console.log('Received message: ', message);
ws.send('Message received: ' + message);
}
}
wss.on('connection', (ws) => {
console.log('New connection');
ws.isAlive = true;
ws.on('pong', () => {
ws.isAlive = true;
});
ws.on('message', (message) => handleMessage(ws, message));
ws.send('Welcome');
});
setInterval(() => {
wss.clients.forEach((ws) => {
if (!ws.isAlive) {
console.log('Connection terminated');
ws.terminate();
}
ws.isAlive = false;
ws.ping();
});
}, 10000);
server.listen('2999', () => {
console.log('Started dev-server at 2999');
});