-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathpreview-server.js
More file actions
51 lines (41 loc) · 1.2 KB
/
preview-server.js
File metadata and controls
51 lines (41 loc) · 1.2 KB
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
const express = require('express')
const http = require('http')
const WebSocket = require('ws')
const path = require('path')
const PORT = 9001
const app = express()
app.get('/', (req, res) => {
// res.sendFile(path.join(__dirname + './../dist/ui.html'));
res.status(200).send('working')
})
//initialize a simple http server
const server = http.createServer(app);
//initialize the WebSocket server instance
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws) => {
ws.isAlive = true;
ws.on('pong', () => {
ws.isAlive = true;
})
//connection is up, let's add a simple simple event
ws.on('message', (message) => {
//send back the message to the other clients
wss.clients.forEach(client => {
if (client != ws) {
client.send(JSON.stringify({message, src: 'server'}));
}
});
})
//send immediatly a feedback to the incoming connection
// ws.send('Hi there, I am a WebSocket server');
})
setInterval(() => {
wss.clients.forEach(ws => {
if (!ws.isAlive) return ws.terminate();
ws.isAlive = false;
ws.ping(null, false, true);
})
}, 10000);
server.listen(PORT, () => {
console.log(`Preview server started on port: ${PORT}`)
})