-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
168 lines (143 loc) · 4.65 KB
/
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
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
const WebSocket = require('ws');
const fs = require('node:fs');
const crypto = require('crypto')
// Создаем WebSocket-сервер на порту 8080
const wss = new WebSocket.Server({ port: process.env.SERVER_PORT || 8080, host: process.env.SERVER_HOST || '127.0.0.1' });
let clients = []
wss.on('connection', (ws, req) => {
console.log('New client connected');
const token = req.headers['sec-websocket-protocol'];
ws.token = token;
const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
initConnection(ws, token, ip);
ws.on('message', (message) => {
const m = JSON.parse(message);
switch (m.type) {
case 'saveState':
saveSate(ws, token, m);
break;
case 'loadState':
loadState(ws, token, m);
break;
case 'clearState':
clearState(ws, token, m);
break;
default:
sendDefault(ws, token, m);
break;
}
});
ws.on('close', () => {
setOnline(ws, token);
console.log('Client disconnected');
});
});
const initConnection = (ws, token, ip) => {
if (!clients[token]) {
clients[token] = [];
}
clients[token].push(ws);
fs.readFile(token === 'default' ? 'state.txt' : `privateStates/${token}.txt`, 'utf8', (err, data) => {
wsSend(ws, {
type: 'initState',
data: err ? '' : data,
online: clients[token].length,
privateRoom: crypto.createHash('md5').update(ip + new Date().toString()).digest("hex"),
palette: getPalette(token)
});
});
clients[token].forEach(client => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
wsSend(client, {
type: 'setOnline',
online: clients[token].length
});
}
});
}
const getPalette = (token) => {
let palette = [];
try {
let f = fs.readFileSync(token === 'default' ? 'state.palette' : `privateStates/${token}.palette`, 'utf8');
palette = f.split(',');
} catch (e) {}
return palette;
}
const saveSate = (ws, token, m) => {
fs.writeFile(token === 'default' ? 'state.txt' : `privateStates/${token}.txt`, m.data, err => {
if (err) {
console.error(err);
}
});
}
const loadState = (ws, token, m) => {
fs.readFile(token === 'default' ? 'state.txt' : `privateStates/${token}.txt`, 'utf8', (err, data) => {
if (err) {
console.error(err);
} else {
wsSend(ws, {
type: 'loadState',
data: data,
online: clients[token].length
});
}
});
}
const clearState = (ws, token, m) => {
fs.readFile(`exampleStates/${token}.txt`, 'utf8', (err, data) => {
let state;
if (!err) {
state = data;
fs.writeFile(token === 'default' ? 'state.txt' : `privateStates/${token}.txt`, state, err => {
if (err) {
console.error(err);
}
});
} else {
state = '';
fs.writeFile(token === 'default' ? 'state.txt' : `privateStates/${token}.txt`, state, err => {
if (err) {
console.error(err);
}
});
}
clients[token].forEach(client => {
if (client.readyState === WebSocket.OPEN) {
wsSend(client, {
type: 'loadState',
data: state,
online: clients[token].length
});
}
});
});
}
const sendDefault = (ws, token, m) => {
// Отправляем сообщение всем подключенным клиентам, кроме отправителя
clients[token].forEach(client => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
wsSend(client, m);
}
});
}
const setOnline = (ws, token) => {
const online = clients[token].length - 1;
clients[token].forEach((client, index) => {
if (client === ws) {
clients[token].splice(index, 1);
if (clients[token].length === 0) {
delete clients[token];
}
}
if (client !== ws && client.readyState === WebSocket.OPEN) {
wsSend(client, {
type: 'setOnline',
online: online
})
}
});
}
const wsSend = (ws, data) => {
ws.send(JSON.stringify(data));
}
console.log('WebSocket сервер запущен на порту 8080');