-
Notifications
You must be signed in to change notification settings - Fork 42
/
receiver.js
44 lines (34 loc) · 996 Bytes
/
receiver.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
var events = require('events');
var util = require('util');
var Receiver = function () {
events.EventEmitter.call(this);
this.sockets = {};
this.data = [];
};
util.inherits(Receiver, events.EventEmitter);
Receiver.prototype.addSocket = function (socket) {
var that = this;
this.sockets[socket.id] = socket;
socket.emit('commands', this.data);
this.emit('request', { cmd: 'init', args: { socket: socket.id } });
socket.on('command', function (data) {
that.emit('request', data);
});
socket.on('disconnect', function () {
socket.removeAllListeners('disconnect');
socket.removeAllListeners('message');
delete(that.sockets[socket.id]);
});
};
Receiver.prototype.send = function (data) {
if (data.cmd === 'init') {
this.sockets[data.args.socket].emit('commands', [ data ]);
return;
}
this.data.push(data);
if (this.data.length > 512) this.data.shift();
for (var id in this.sockets) {
this.sockets[id].emit('commands', [ data ]);
}
};
module.exports = Receiver;