-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
232 lines (173 loc) Β· 4.59 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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
/**
* @author pschroen / https://ufo.ai/
*
* Remix of https://glitch.com/edit/#!/multiuser-sketchpad
*/
import express from 'express';
import enableWs from 'express-ws';
const interval = 4000; // 4 second heartbeat
const app = express();
const expressWs = enableWs(app);
expressWs.getWss('/');
app.use(express.static('public'));
//
import { ObjectPool } from '@alienkitty/space.js/three';
import { numPointers } from './src/config/Config.js';
const mousePool = new ObjectPool();
for (let i = 0; i < numPointers; i++) {
mousePool.put(i);
}
//
const clients = [];
const room = new Array(255);
function getRemoteAddress(request) {
return (request.headers['x-forwarded-for'] || request.connection.remoteAddress).split(',')[0].trim();
}
function getRemoteAddresses() {
return clients.map(ws => ws._remoteAddress);
}
function getUsers() {
if (!clients.length) {
return;
}
const length = clients.length;
const byteLength = 1 + 10 + 4 + 2; // mouse + nickname + remoteAddress + latency
const data = Buffer.allocUnsafe(1 + byteLength * length); // event + size * users
data.writeUInt8(0, 0);
let index = 1;
for (let i = 0; i < length; i++) {
const client = clients[i];
data.writeUInt8(client._mouse === null ? numPointers : client._mouse, index);
const buf = Buffer.from(client._nickname, 'utf8');
for (let j = 0; j < 10; j++) {
data.writeUInt8(buf[j], index + 1 + j);
}
data.writeUInt32BE(ip2long(client._remoteAddress), index + 11);
data.writeUInt16BE(client._latency, index + 15);
index += byteLength;
}
// console.log('USERS:', data);
return data;
}
function add(ws, request) {
clients.push(ws);
for (let i = 0, l = room.length; i < l; i++) {
if (room[i] === undefined) {
const remoteAddresses = getRemoteAddresses();
let count = 1;
let remoteAddress = getRemoteAddress(request);
while (remoteAddresses.includes(remoteAddress)) {
count++;
remoteAddress = `${getRemoteAddress(request)} (${count})`;
}
ws._id = i;
ws._idle = Date.now();
ws._mouse = request.query.observer !== undefined ? null : mousePool.get();
ws._nickname = '';
ws._remoteAddress = remoteAddress;
ws._latency;
room[i] = ws;
console.log('REMOTE:', ws._remoteAddress, request.headers['user-agent']);
return;
}
}
}
function remove(ws) {
let index = clients.indexOf(ws);
if (~index) {
clients.splice(index, 1);
}
index = room.indexOf(ws);
if (~index) {
room[index] = undefined;
}
if (ws._mouse !== null) {
mousePool.put(ws._mouse);
}
}
function broadcast(ws, data) {
for (let i = 0, l = clients.length; i < l; i++) {
const client = clients[i];
if (client !== ws && client.readyState === client.OPEN) {
client.send(data);
}
}
}
function idle() {
const idleTime = Date.now() - 1800000; // 30 * 60 * 1000
for (let i = 0, l = clients.length; i < l; i++) {
const client = clients[i];
if (client._idle === 0) {
client._idle = Date.now();
} else if (client._idle < idleTime) {
client.terminate();
console.log('IDLE:', client._id);
}
}
}
function users(ws) {
broadcast(ws, getUsers());
}
app.ws('/', (ws, request) => {
add(ws, request);
console.log('USERS:', clients.length);
ws.on('close', () => {
remove(ws);
users(ws);
console.log('USERS:', clients.length);
});
ws.on('message', data => {
ws._idle = 0;
switch (data.readUInt8(0)) {
case 1:
// console.log('HEARTBEAT:', data);
ws._latency = Math.min(65535, Date.now() - Number(data.readBigUInt64BE(2))); // Clamp to 65535
break;
case 2: {
if (ws._mouse !== null) {
// console.log('NICKNAME:', data);
ws._nickname = Buffer.from(data.subarray(2), 'utf-8').toString();
users(ws);
}
break;
}
case 3: {
if (ws._mouse !== null) {
data.writeUInt8(ws._mouse, 1);
// console.log('MOTION:', data);
broadcast(ws, data);
}
}
}
// console.log('MESSAGE:', data);
});
const heartbeat = () => {
if (ws.readyState === ws.OPEN) {
const data = Buffer.allocUnsafe(10);
data.writeUInt8(1, 0);
data.writeUInt8(ws._mouse === null ? numPointers : ws._mouse, 1);
data.writeBigUInt64BE(BigInt(Date.now()), 2);
ws.send(data);
setTimeout(heartbeat, interval);
}
};
heartbeat();
users();
});
setInterval(() => {
idle();
users();
}, interval);
//
const listener = app.listen(process.env.PORT, () => {
console.log(`Listening on port ${listener.address().port}`);
});
// https://stackoverflow.com/questions/1908492/unsigned-integer-in-javascript/7414641#7414641
function ip2long(ip) {
let ipl = 0;
ip.split('.').forEach(octet => {
ipl <<= 8;
ipl += parseInt(octet, 10);
});
return ipl >>> 0;
}