-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
88 lines (77 loc) · 2.37 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
const WebSocket = require('ws');
const Redis = require('ioredis');
const redis = new Redis({ host: 'redis' });
const wss = new WebSocket.Server({ port: 7379 });
wss.on('connection', function connection(ws) {
let isServer = false;
let remoteIp = ws._socket.remoteAddress.replace(/^.*:/, '');
ws.on('close', function close() {
if (isServer) {
redis.get('server', function (err, result) {
if (!err && result && result == remoteIp) {
redis.set('server', null);
console.log('server stopped: %s', remoteIp);
}
});
}
});
ws.on('message', function incoming(payload) {
let json = JSON.parse(payload);
let message = json.message;
let type = json.type;
switch (type) {
// message: { query: server }
case 'lookup': {
redis.get('server', function (err, result) {
ws.send(JSON.stringify({
version: 1,
type: 'lookup',
message: {
ip: err || result == null ? '' : result
}
}));
});
} break;
// message: { status: online || offline }
case 'status': {
if (message.status == 'online') {
redis.set('server', remoteIp);
isServer = true;
console.log('server started: %s', remoteIp);
}
else {
redis.set('server', null);
}
} break;
// message: { event: hit, id: name, value: 1 }
case 'player': {
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(payload);
}
});
} break;
// message: { server: ip, id: Asteroid, params: [0, 1, 2] }
case 'spawn': {
redis.get('server', function (err, result) {
if (!err && result) {
wss.clients.forEach(client => {
let clientIp = client._socket.remoteAddress.replace(/^.*:/, '');
if (result == clientIp) {
client.send(JSON.stringify({
version: 1,
type: 'spawn',
message: {
id: message.id,
params: message.params || []
}
}));
}
});
}
});
} break;
}
console.log('received: %s', JSON.stringify(json));
});
});