From 43658264a859eea074bc0d30a8fb756bd45fd6ff Mon Sep 17 00:00:00 2001 From: wltsmrz Date: Wed, 16 Jul 2014 18:00:15 -0700 Subject: [PATCH] Possible fix for 'WebSocket is closed before the connection is established' error --- src/js/ripple/server.js | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/src/js/ripple/server.js b/src/js/ripple/server.js index 9d8ef0f3..dc18c864 100644 --- a/src/js/ripple/server.js +++ b/src/js/ripple/server.js @@ -300,8 +300,18 @@ Server.prototype.getHostID = function() { */ Server.prototype.disconnect = function() { + var self = this; + + if (!this._connected) { + this.once('socket_open', function() { + self.disconnect(); + }); + return; + } + this._shouldConnect = false; this._setState('offline'); + if (this._ws) { this._ws.close(); } @@ -317,6 +327,7 @@ Server.prototype.reconnect = function() { var self = this; function disconnected() { + self._shouldConnect = true; self.connect(); }; @@ -459,15 +470,15 @@ Server.prototype._handleClose = function() { var self = this; var ws = this._ws; - this.emit('socket_close'); - this._setState('offline'); - function noOp(){}; // Prevent additional events from this socket ws.onopen = ws.onerror = ws.onclose = ws.onmessage = noOp; - if (self._shouldConnect) { + this.emit('socket_close'); + this._setState('offline'); + + if (this._shouldConnect) { this._retryConnect(); } }; @@ -682,13 +693,14 @@ Server.prototype._request = function(request) { var isSubscribeRequest = request && request.message.command === 'subscribe' && this._ws.readyState === 1; - if (this._isConnected() || isSubscribeRequest) { + if (this.isConnected() || isSubscribeRequest) { sendRequest(); } else { this.once('connect', sendRequest); } }; +Server.prototype.isConnected = Server.prototype._isConnected = function() { return this._connected; };