-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
46 lines (43 loc) · 1.25 KB
/
index.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
'use strict';
var
tls = require('tls'),
StateEmitter = require('state-emitter').StateEmitter;
module.exports = function (codec) {
var
ondata,
socket,
connected = true,
disconnected = false,
state = new StateEmitter();
return {
connect: function (port, host) {
socket = tls.connect(port, host, function () {
state.next(connected);
});
socket.on('data', codec.decode);
socket.on('end', function () {
state.next(disconnected);
});
socket.on('error', function () {
state.next(disconnected);
});
},
send: function (message) {
socket.write(
codec.encode(message.payloadType, message.payload, message.clientMsgId)
);
},
onOpen: function (callback) {
state.whenEqual(connected, callback);
},
onEnd: function (callback) {
state.whenEqual(disconnected, callback);
},
onError: function (callback) {
state.whenEqual(disconnected, callback);
},
onData: function (callback) {
codec.subscribe(callback);
}
};
};