-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathserver.js
82 lines (69 loc) · 2.1 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
var WebSocket = new require('ws');
var argv = require('minimist')(process.argv.slice(2), {string: ['port'], default: {port: 1207}});
var server = new WebSocket.Server({
clientTracking: true,
port: argv['port']
}, function () {
console.log('WebSocket server started on port: ' + argv['port']);
});
var shutdown = function () {
console.log('Received kill signal, shutting down gracefully.');
server.close(function () {
console.log('Closed out remaining connections.');
process.exit();
});
setTimeout(function () {
console.error('Could not close connections in time, forcefully shutting down');
process.exit();
}, 10 * 1000);
};
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);
server.on('error', function (err) {
console.log(err);
});
var hexColorRegExp = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;
var typeRegExp = /^(top|bottom|right)$/;
var msgMinInterval = 500;
var lastMsgTimestamps = {};
server.on('connection', function (ws, req) {
var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
ws.on('message', function (message) {
var time = Date.now();
if (lastMsgTimestamps[ip] && lastMsgTimestamps[ip] - time < msgMinInterval) {
return;
}
try {
message = JSON.parse(message);
if (!hexColorRegExp.test(message.color) || !typeRegExp.test(message.type) || !message.text) {
return;
}
var msg = {
text: message.text.substr(0, 255),
color: message.color,
type: message.type
};
} catch (e) {
return;
}
console.log(msg);
lastMsgTimestamps[ip] = time;
var data = JSON.stringify(msg);
server.clients.forEach(function (client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(data, function (err) {
err && console.log(err);
});
}
});
});
ws.on('error', console.log);
});
setInterval(function () {
var time = Date.now();
Object.keys(lastMsgTimestamps).forEach(function (key) {
if (time - lastMsgTimestamps[key] > msgMinInterval) {
delete lastMsgTimestamps[key];
}
});
}, 5000);