-
Notifications
You must be signed in to change notification settings - Fork 2
/
LazySocket.js
85 lines (66 loc) · 1.84 KB
/
LazySocket.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
var net = require('net');
module.exports = LazySocket;
function LazySocket(properties) {
properties = properties || {};
this.port = properties.port;
this.host = properties.host;
this.timeout = properties.timeout || 0;
this._socket = null;
this._callbacks = [];
}
LazySocket.createConnection = function(port, host, timeout) {
var socket = new this({port: port, host: host, timeout: timeout});
return socket;
};
LazySocket.prototype.write = function(/* data, encoding, cb */) {
var self = this;
var args = Array.prototype.slice.call(arguments);
var cb = args[args.length - 1];
if (typeof cb === 'function') {
var cbProxy = function() {
var index = self._callbacks.indexOf(cbProxy);
if (index < 0) {
// callback has already been called and removed from the
// callback list
return;
}
self._callbacks.splice(index, 1);
return cb.apply(this, arguments);
};
args[args.length - 1] = cbProxy;
this._callbacks.push(cbProxy);
}
this._lazyConnect();
try {
this._socket.write.apply(this._socket, args);
} catch (err) {
if (cbProxy) cbProxy(err);
this._socket.destroy();
this._socket = null;
}
};
LazySocket.prototype._lazyConnect = function() {
if (this._socket) return;
var self = this;
var onerror = function(err) {
self._socket = null;
self._callbacks.forEach(function(cb) {
cb(err);
});
};
this._socket = net
.createConnection(this.port, this.host)
.once('error', onerror);
if (this.timeout) {
this._socket.setTimeout(this.timeout, function() {
self._socket.end();
onerror('timeout');
});
}
};
LazySocket.prototype.end = function() {
if (this._socket) this._socket.end();
};
LazySocket.prototype.destroy = function() {
if (this._socket) this._socket.destroy();
};