Repository navigation
Expand file tree
/
Copy pathCommunication.js
More file actions
51 lines (44 loc) · 1.64 KB
/
Copy pathCommunication.js
File metadata and controls
51 lines (44 loc) · 1.64 KB
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
var enumFactory = require('simple-enum'), events = require('events'), net = require('net'), util = require('util');
connectionStates = enumFactory(['Disconnected', 'Connected']);
function Communication(host, port) {
this.client = null;
this.messagesReceived = 0;
this.bytesReceived = 0;
var host = host;
var port = port;
var connectionState = connectionStates.Disconnected;
events.EventEmitter.call(this);
this.connect = function() {
if(connectionState === connectionStates.Disconnected) {
var origin = this;
this.client = net.connect({ host: host, port: port }, function() {
connectionState = connectionStates.Connected;
origin.emit('connected');
console.log('[Communication::connect][Info]: Connected to `' + host + ':' + port + '`.');
});
this.client.on('end', function() {
connectionState = connectionStates.Disconnected;
console.log('[Communication::connect][Info]: Connection lost.');
origin.emit('lost', { code: 'ECONNLOST' });
})
this.client.on('error', function(e) {
console.log('[Communication::connect][Error]:', e);
origin.emit('error', e);
});
} else
console.log('[Communication::connect][Error]: Connection is already made!');
}
this.send = function(data) {
if(connectionState === connectionStates.Connected) {
var origin = this;
this.client.on('data', function(bytes) {
origin.messagesReceived++;
origin.emit('receivedBytes', bytes);
});
this.client.write(data);
} else
console.log('[Communication::send][Error]: Can not send data - client is disconnected.');
}
}
util.inherits(Communication, events.EventEmitter);
module.exports = Communication;