forked from basharmadi/node-whatsapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transport.js
61 lines (47 loc) · 1.32 KB
/
transport.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
53
54
55
56
57
58
59
60
61
var net = require('net');
function Socket() {
this.callbacks = {
receive : null,
error : null,
end : null
};
}
Socket.prototype.connect = function(host, port, callback, thisarg) {
this.socket = net.connect({
port : port,
host : host
}, callback && callback.bind(thisarg));
this.socket.on('error', function() {
this.callbacks.error && this.callbacks.error.apply(this, arguments);
}.bind(this));
this.socket.on('end', function() {
this.callbacks.end && this.callbacks.end.apply(this, arguments);
}.bind(this));
this.socket.on('data', function() {
this.callbacks.receive && this.callbacks.receive.apply(this, arguments);
}.bind(this));
};
Socket.prototype.send = function(data) {
if(!this.socket) {
throw 'Trying to send data whilst no connection established';
}
this.socket.write(data);
};
Socket.prototype.disconnect = function() {
if(!this.socket) {
return;
}
this.socket.removeAllListeners();
this.socket.destroy();
this.socket = null;
};
Socket.prototype.onReceive = function(callback, thisarg) {
this.callbacks.receive = callback.bind(thisarg);
};
Socket.prototype.onError = function(callback, thisarg) {
this.callbacks.error = callback.bind(thisarg);
};
Socket.prototype.onEnd = function(callback, thisarg) {
this.callbacks.end = callback.bind(thisarg);
};
exports.Socket = Socket;