-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.js
52 lines (45 loc) · 1.41 KB
/
connection.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
var net = require('net');
var events = require('events');
var msg = require('./messages.js');
exports.ClientManager = function(maxConnections) {
this.connect = function(port,address,callback) {
var socket = new net.Socket();
socket.on('data', function(data) {
console.log('\x1b[37;1mdata from: '+this.remoteAddress+':'+this.remotePort+' \x1b[0m'+data.toString());
var dataText = data.toString();
var json,data;
if ( dataText.search("}{") > -1 )
{
while ( ( frameBreak = dataText.search("}{") ) > -1 )
{
json = dataText.substr(0,frameBreak+1);
dataText = dataText.substr(frameBreak+1);
data = JSON.parse(json);
data.socket = this;
exports.eventEmitter.emit('processMessage',data);
}
}
data = JSON.parse(dataText);
data.socket = this;
exports.eventEmitter.emit('processMessage',data);
});
socket.on('error', function(e) {
console.log(e.code);
exports.disconnect(this);
});
socket.on('end', function() {
console.log('\x1b[31mdisconnecting from '+this.remoteAddress_+':'+this.remotePort_+'\x1b[0m');
exports.disconnect(this);
});
socket.connect(port,address, function() {
if (typeof callback == "function")
{
callback(this.remotePort,this.remoteAddress);
this.remotePort_ = this.remotePort;
this.remoteAddress_ = this.remoteAddress;
}
});
}
}
//Singleton
exports.clientManager = new exports.ClientManager(maxRoutes);