diff --git a/lib/nssocket.js b/lib/nssocket.js index 762e306..5f72b13 100644 --- a/lib/nssocket.js +++ b/lib/nssocket.js @@ -61,7 +61,8 @@ var NsSocket = exports.NsSocket = function (socket, options) { retries: 0, max: options.maxRetries || 10, interval: options.retryInterval || 5000, - wait: options.retryInterval || 5000 + wait: options.retryInterval || 5000, + pendingReconnect: false }; // @@ -308,6 +309,9 @@ NsSocket.prototype.connect = function connect(/*port, host, callback*/) { // NsSocket.prototype.reconnect = function reconnect() { var self = this; + if(self.retry.pendingReconnect) + return; + self.retry.pendingReconnect = true; // // Helper function containing the core reconnect logic @@ -317,16 +321,16 @@ NsSocket.prototype.reconnect = function reconnect() { // Cleanup and recreate the socket associated // with this instance. // - self.retry.waiting = true; self.socket.removeAllListeners(); self.socket = common.createSocket(self._options); + self.retry.pendingReconnect = false; // // Cleanup reconnect logic once the socket connects // self.socket.once('connect', function () { - self.retry.waiting = false; self.retry.retries = 0; + self._onStart(); }); // @@ -342,15 +346,19 @@ NsSocket.prototype.reconnect = function reconnect() { // function tryReconnect() { self.retry.retries++; - if (self.retry.retries >= self.retry.max) { + if (self.retry.max >= 0 && self.retry.retries >= self.retry.max) { return self.emit('error', new Error('Did not reconnect after maximum retries: ' + self.retry.max)); } doReconnect(); } - this.retry.wait = this.retry.interval * Math.pow(10, this.retry.retries); - setTimeout(tryReconnect, this.retry.wait); + // retry interval follows a kind of Sigmoid function + // it will be limited to 5 * (initial interval) + this.retry.wait = this.retry.interval * (5 - 4*Math.pow(1.5, -this.retry.retries)); + if(this.retry.reconnectTimeout) + clearTimeout(this.retry.reconnectTimeout); + this.retry.reconnectTimeout = setTimeout(tryReconnect, this.retry.wait * 1000); }; //