forked from kokarn/tarkov-socket-server
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.mjs
101 lines (78 loc) · 2.44 KB
/
server.mjs
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import dotenv from 'dotenv';
import WebSocket, { WebSocketServer } from 'ws';
dotenv.config();
const wss = new WebSocketServer({
port: process.env.PORT || 8080,
});
const sendMessage = (sessionID, type, data) => {
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN && client.sessionID === sessionID) {
client.send(JSON.stringify({
type: type,
data: data,
}));
}
});
};
const pingInterval = setInterval(() => {
console.log(`active clients: ${wss.clients.size}`);
wss.clients.forEach((client) => {
// if ping is pending from last tick, no response was received
// so we terminate the connection
if (client.pingPending === true) {
console.log(`terminating ${client.sessionID}`);
return client.terminate();
}
client.pingPending = true;
client.send(JSON.stringify({
type: 'ping',
}));
});
}, 30000);
wss.on('connection', (ws, req) => {
const url = new URL(`http://localhost${req.url}`);
ws.sessionID = url.searchParams.get('sessionid');
if (!ws.sessionID) {
//console.log('Terminating connecting client missing sessionID');
ws.terminate();
return;
}
console.log(`Client connected ${ws.sessionID}`);
ws.pingPending = false;
ws.settings = {};
ws.on('message', (rawMessage) => {
const message = JSON.parse(rawMessage);
if (message.type === 'pong') {
ws.pingPending = false;
return;
}
if (message.type !== 'debug') {
console.log(ws.sessionID, message);
}
const sessionID = message.sessionID;
if (!sessionID) {
console.log('No session ID set, dropping message', message);
return;
}
if (message.type === 'command') {
sendMessage(sessionID, 'command', message.data);
return;
}
if (message.type === 'debug') {
sendMessage(sessionID, 'debug', message.data);
return;
}
});
ws.on('close', () => {
console.log(`Client disconnected ${ws.sessionID}`);
});
});
wss.on('error', error => {
console.error('Server error', error);
});
wss.on('close', () => {
clearInterval(pingInterval);
});
process.on('uncaughtException', (error) => {
console.error('Uncaught Exception', error.stack);
});