mirror of
https://gitlab.com/wgp/dougal/software.git
synced 2025-12-06 12:57:08 +00:00
56 lines
1.3 KiB
JavaScript
56 lines
1.3 KiB
JavaScript
const ws = require('ws');
|
|
const URL = require('url');
|
|
const db = require('./db');
|
|
|
|
function start (server, pingInterval=30000) {
|
|
|
|
const channels = [
|
|
"realtime", "event", "project",
|
|
"preplot_lines", "preplot_points",
|
|
"planned_lines",
|
|
"raw_lines", "raw_shots",
|
|
"final_lines", "final_shots", "info"
|
|
];
|
|
|
|
const wsServer = new ws.Server({ noServer: true });
|
|
wsServer.on('connection', socket => {
|
|
socket.alive = true;
|
|
socket.on('pong', function () { this.alive = true; })
|
|
socket.on('message', message => console.log(message));
|
|
});
|
|
|
|
server.on('upgrade', (request, socket, head) => {
|
|
// console.log("Received upgrade request", request.url);
|
|
const url = URL.parse(request.url);
|
|
if (/^\/ws\/?$/.test(url.pathname)) {
|
|
wsServer.handleUpgrade(request, socket, head, socket => {
|
|
wsServer.emit('connection', socket, request);
|
|
});
|
|
}
|
|
});
|
|
|
|
db.listen(channels, (data) => {
|
|
wsServer.clients.forEach( (socket) => {
|
|
socket.send(JSON.stringify(data));
|
|
})
|
|
});
|
|
|
|
const interval = setInterval( () => {
|
|
wsServer.clients.forEach( (socket) => {
|
|
if (!socket.alive) {
|
|
return socket.terminate();
|
|
}
|
|
socket.alive = false;
|
|
socket.ping();
|
|
})
|
|
}, pingInterval);
|
|
|
|
wsServer.on('close', () => clearInterval(interval));
|
|
|
|
return wsServer;
|
|
}
|
|
|
|
module.exports = {
|
|
start
|
|
}
|