-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathagent.js
47 lines (36 loc) · 1023 Bytes
/
agent.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
var events = require('events');
var Agent = function () {
this.lastId = 0;
// TODO: Is it effetive way to manage mutable dictionary in V8.
this.clients = {};
var agent = this;
this.onConnected = function(client) {
var clientId = this.lastId += 1;
this.clients[clientId] = client;
client.id = clientId;
console.log('client', clientId, 'connected');
client.on('end', function() {
delete agent.clients[clientId];
console.log('client', clientId, 'disconnected');
});
// TODO: Package completeness check.
client.on('data', function(data) {
try {
var position = JSON.parse(data);
position.clientId = clientId;
} catch (err) {
console.log(err);
return;
}
agent.broadcast(position);
});
};
this.broadcast = function(message) {
Object.keys(this.clients).forEach(function(id) {
var c = agent.clients[id];
c.write(JSON.stringify(message));
});
};
};
Agent.prototype.__proto__ = events.EventEmitter.prototype;
exports.Agent = Agent;