-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
70 lines (60 loc) · 1.99 KB
/
index.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
const net = require('net');
const http = require('http');
const WebSocket = require('ws');
const server = http.createServer((req, res) => {
if (req.method === 'GET') {
const url = new URL(req.url, 'http://localhost');
const subText = url.searchParams.get('sub-text');//.trim();
const timePos = url.searchParams.get('time');
let secondarySubText = url.searchParams.get('secondary-sub-text');//.trim()
if (subText && subText !== "undefined") {
if (secondarySubText === "undefined") secondarySubText = null;
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({subText, secondarySubText, timePos}));
}
});
res.end('Message relayed via WebSocket\n');
} else {
res.end('No message provided\n');
}
} else {
res.end('Hello World\n');
}
});
const wss = new WebSocket.Server({ server });
// Handle WebSocket connections
/* wss.on('connection', (ws) => {
console.log('WebSocket connection established');
ws.on('message', (message) => {
console.log(`Received message: ${message}`);
});
ws.on('close', () => {
console.log('WebSocket connection closed');
});
});
*/
const ensureServerIsRunning = (startup) => {
const tester = net.createServer();
tester.once('error', (err) => {
if (err.code === 'EADDRINUSE') {
if (startup) {
console.log('Port 21659 is already in use');
}
}
});
tester.once('listening', () => {
tester.close();
if (startup) {
console.log('Port 21659 is available');
}
server.listen(21659, () => {
if (startup) {
console.log('Server listening on port 21659');
}
});
});
tester.listen(21659)
}
ensureServerIsRunning(true)
setInterval(() => { ensureServerIsRunning(false) }, 1000)