Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 14 additions & 6 deletions lib/nssocket.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
};

//
Expand Down Expand Up @@ -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
Expand All @@ -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();
});

//
Expand All @@ -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);
};

//
Expand Down