aboutsummaryrefslogtreecommitdiffstats
path: root/lib/assets
diff options
context:
space:
mode:
authorPratik Naik <pratiknaik@gmail.com>2015-02-26 14:25:34 -0600
committerPratik Naik <pratiknaik@gmail.com>2015-02-26 14:25:34 -0600
commit359f006bac5318fa3f61b2c20f45bd7ec90b0de1 (patch)
tree22113779668121dbd5c549fa05a7aa95d1493961 /lib/assets
parent247453adec8e506c641c6c3d3d06709d835f435f (diff)
downloadrails-359f006bac5318fa3f61b2c20f45bd7ec90b0de1.tar.gz
rails-359f006bac5318fa3f61b2c20f45bd7ec90b0de1.tar.bz2
rails-359f006bac5318fa3f61b2c20f45bd7ec90b0de1.zip
Reconnect the websocket if the server doesnt send a ping every 6 seconds
Diffstat (limited to 'lib/assets')
-rw-r--r--lib/assets/javascripts/cable.js.coffee22
1 files changed, 18 insertions, 4 deletions
diff --git a/lib/assets/javascripts/cable.js.coffee b/lib/assets/javascripts/cable.js.coffee
index 2a70693bf0..2b34c1b447 100644
--- a/lib/assets/javascripts/cable.js.coffee
+++ b/lib/assets/javascripts/cable.js.coffee
@@ -4,7 +4,7 @@
class @Cable
MAX_CONNECTION_ATTEMPTS: 10
MAX_CONNECTION_INTERVAL: 5 * 1000
- MAX_PING_INTERVAL: 6
+ PING_STALE_INTERVAL: 6
constructor: (@cableUrl) ->
@subscribers = {}
@@ -40,6 +40,7 @@ class @Cable
@subscribers[data.identifier]?.onReceiveData(data.message)
connected: =>
+ @startWaitingForPing()
@resetConnectionAttemptsCount()
for identifier, callbacks of @subscribers
@@ -47,6 +48,7 @@ class @Cable
callbacks['onConnect']?()
reconnect: =>
+ @clearPingWaitTimeout()
@resetPingTime()
@disconnected()
@@ -71,7 +73,18 @@ class @Cable
interval = (Math.pow(2, @connectionAttempts) - 1) * 1000
if interval > @MAX_CONNECTION_INTERVAL then @MAX_CONNECTION_INTERVAL else interval
- resetPingTime: () =>
+ startWaitingForPing: =>
+ @clearPingWaitTimeout()
+
+ @waitForPingTimeout = setTimeout =>
+ console.log "Ping took too long to arrive. Reconnecting.."
+ @connection?.close()
+ , @PING_STALE_INTERVAL * 1000
+
+ clearPingWaitTimeout: =>
+ clearTimeout(@waitForPingTimeout)
+
+ resetPingTime: =>
@lastPingTime = null
disconnected: =>
@@ -100,8 +113,9 @@ class @Cable
@connection.send JSON.stringify { action: 'unsubscribe', identifier: identifier }
pingReceived: (timestamp) =>
- if @lastPingTime? and (timestamp - @lastPingTime) > @MAX_PING_INTERVAL
+ if @lastPingTime? and (timestamp - @lastPingTime) > @PING_STALE_INTERVAL
console.log "Websocket connection is stale. Reconnecting.."
- @connection.close()
+ @connection?.close()
else
+ @startWaitingForPing()
@lastPingTime = timestamp