This repository has been archived by the owner on Jul 17, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
62 lines (54 loc) · 1.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
'use strict';
var WebSocketServer = require('ws').Server,
sleep = require('sleep'),
isTrackerOn,
screenWidth = 1280,
screenHeight = 1920,
clients = [],
port = parseInt(process.argv[2], 10) || 8887,
emitFrequencyMs = parseInt(process.argv[3], 10) || 30,
wss = new WebSocketServer({
port: port
});
console.log('The server has started on port: ' + port);
wss.on('connection', function (ws) {
clients.push(ws);
console.log('a client connected');
ws.on('close', function (code, message) {
clients.splice(clients.indexOf(ws), 1);
console.log('a client disconnected');
});
ws.on('message', function (message) {
handleEyeNavMessage(message);
console.log('a client sent message: "' + message + '"');
});
});
function handleEyeNavMessage(message) {
switch (message) {
case 'startTracker':
startTracker();
break;
case 'stopTracker':
isTrackerOn = false;
break;
}
}
function startTracker() {
isTrackerOn = true;
var intervalEmitter = setInterval(function () {
broadcast({
state: 1,
timestamp: Date.now(),
x: ~~(Math.random() * screenWidth),
y: ~~(Math.random() * screenHeight)
});
if (!isTrackerOn) {
clearInterval(intervalEmitter);
}
}, emitFrequencyMs);
}
function broadcast(jsonObject) {
clients.forEach(function (elem) {
elem.send(JSON.stringify(jsonObject));
});
}