diff --git a/lib/LazySocket.js b/lib/LazySocket.js index 80fa8d3..56daf2c 100644 --- a/lib/LazySocket.js +++ b/lib/LazySocket.js @@ -8,6 +8,7 @@ function LazySocket(properties) { this.host = properties.host; this._socket = null; + this._closed = false; this._callbacks = []; } @@ -57,15 +58,28 @@ LazySocket.prototype._lazyConnect = function() { }); } + function onend() { + // "end" is called when the socket connection is terminated, regardless of the termination being unexpected or not + // to distinguish between unexpected terminations (e.g need reconnection) + // from expected terminations (e.g calling LazySocket's .end() or .destroy()), the later are flagged as "closed" + + if (!self._closed) { + self._socket = null; + } + } + this._socket = net .createConnection(this.port, this.host) - .once('error', onerror); + .once('error', onerror) + .once('end', onend); }; LazySocket.prototype.end = function() { + this._closed = true; if (this._socket) this._socket.end(); }; LazySocket.prototype.destroy = function() { + this._closed = true; if (this._socket) this._socket.destroy(); };