-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproducer.js
47 lines (41 loc) · 1.1 KB
/
producer.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
/*
producer.js - Producer module for use in Simple NTP Service
*/
var io = require('socket.io');
var consumers = {};
var consumerCount = 0;
function sendTime() {
for (var id in consumers) {
// only send timestamp to "alive" Consumers
if ((Date.now() - consumers[id].keepAlive) >= 10000) {
delete consumers[id];
} else {
consumers[id].socket.emit('Time', Date.now());
}
}
}
// initialize Producer, accept Register and KeepAlive messages
module.exports.init = function(port) {
var ioProducer = io.listen(port);
ioProducer.on('connection', function(socket) {
socket.on('Register', function() {
consumers[consumerCount++] = {
socket: socket,
keepAlive: Date.now()
};
});
socket.on('KeepAlive', function() {
for (var id in consumers) {
// confirm identity with socket
if (socket == consumers[id].socket) {
consumers[id].keepAlive = Date.now();
}
}
});
});
};
// start sending timestamps
module.exports.start = function() {
// send timestamp every second
setInterval(sendTime, 1000);
};