From c5fdb3e2f68d506bec5476a04a36c1abb807211e Mon Sep 17 00:00:00 2001 From: Matthew Fettig Date: Sun, 13 Jul 2014 20:11:00 -0700 Subject: [PATCH] [FEATURE] reconnect servers when browser comes online --- src/js/ripple/remote.js | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/src/js/ripple/remote.js b/src/js/ripple/remote.js index eed4d4ef..f697f9eb 100644 --- a/src/js/ripple/remote.js +++ b/src/js/ripple/remote.js @@ -101,7 +101,8 @@ function Remote(opts, trace) { this._transaction_subs = 0; this._connection_count = 0; this._connected = false; - + this._persist = false; + this._connection_offset = 1000 * (typeof opts.connection_offset === 'number' ? opts.connection_offset : 0); this._submission_timeout = 1000 * (typeof opts.submission_timeout === 'number' ? opts.submission_timeout : 10); @@ -249,6 +250,32 @@ function Remote(opts, trace) { self._pingInterval = setInterval(pingServers, opts.ping * 1000); }); } + + //if we are using a browser, reconnect + //the servers whenever the network comes online + if (typeof window !== 'undefined') { + if (window.addEventListener) { // W3C DOM + window.addEventListener('online', reconnect); + } else if (window.attachEvent) { // IE DOM + window.attachEvent('ononline', reconnect); + } + } + + function reconnect() { + if (!self._persist) { + return; + } + + log.info('reconnecting'); + + ;(function nextServer(i) { + self._servers[i].reconnect(); + var next = nextServer.bind(this, ++i); + if (i < self._servers.length) { + setTimeout(next, self._connection_offset); + } + })(0); + } }; util.inherits(Remote, EventEmitter); @@ -514,7 +541,8 @@ Remote.prototype.connect = function(online) { } var self = this; - + this._persist = true; + ;(function nextServer(i) { self._servers[i].connect(); var next = nextServer.bind(this, ++i); @@ -542,6 +570,7 @@ Remote.prototype.disconnect = function(callback) { this.once('disconnect', callback); } + this._persist = false; this._servers.forEach(function(server) { server.disconnect(); });