mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Update connection API with #open, #close, #reopen
This commit is contained in:
parent
315c0fbf19
commit
5541b8fcaf
2 changed files with 21 additions and 20 deletions
|
@ -3,39 +3,41 @@
|
|||
class Cable.Connection
|
||||
constructor: (@consumer) ->
|
||||
new Cable.ConnectionMonitor @consumer
|
||||
@connect()
|
||||
@open()
|
||||
|
||||
send: (data) ->
|
||||
if @isConnected()
|
||||
if @isOpen()
|
||||
@websocket.send(JSON.stringify(data))
|
||||
true
|
||||
else
|
||||
false
|
||||
|
||||
connect: ->
|
||||
@removeWebsocket()
|
||||
@createWebSocket()
|
||||
|
||||
createWebSocket: ->
|
||||
open: ->
|
||||
@websocket = new WebSocket(@consumer.url)
|
||||
@websocket.onmessage = @onMessage
|
||||
@websocket.onopen = @onConnect
|
||||
@websocket.onopen = @onOpen
|
||||
@websocket.onclose = @onClose
|
||||
@websocket.onerror = @onError
|
||||
@websocket
|
||||
|
||||
removeWebsocket: ->
|
||||
if @websocket?
|
||||
@websocket.onclose = -> # no-op
|
||||
@websocket.onerror = -> # no-op
|
||||
@websocket.close()
|
||||
@websocket = null
|
||||
close: ->
|
||||
@websocket.close() unless @isClosed()
|
||||
|
||||
reopen: ->
|
||||
@close()
|
||||
@open()
|
||||
|
||||
isOpen: ->
|
||||
@websocket.readyState is WebSocket.OPEN
|
||||
|
||||
isClosed: ->
|
||||
@websocket.readyState in [ WebSocket.CLOSED, WebSocket.CLOSING ]
|
||||
|
||||
onMessage: (message) =>
|
||||
data = JSON.parse message.data
|
||||
@consumer.subscribers.notify(data.identifier, "received", data.message)
|
||||
|
||||
onConnect: =>
|
||||
onOpen: =>
|
||||
@consumer.subscribers.reload()
|
||||
|
||||
onClose: =>
|
||||
|
@ -43,10 +45,9 @@ class Cable.Connection
|
|||
|
||||
onError: =>
|
||||
@disconnect()
|
||||
|
||||
isConnected: ->
|
||||
@websocket?.readyState is 1
|
||||
@websocket.onclose = -> # no-op
|
||||
@websocket.onerror = -> # no-op
|
||||
try @close()
|
||||
|
||||
disconnect: ->
|
||||
@consumer.subscribers.notifyAll("disconnected")
|
||||
@removeWebsocket()
|
||||
|
|
|
@ -35,7 +35,7 @@ class Cable.ConnectionMonitor
|
|||
reconnect: ->
|
||||
console.log "Ping took too long to arrive. Reconnecting.."
|
||||
@connectionAttempts += 1
|
||||
@consumer.connection.connect()
|
||||
@consumer.connection.reopen()
|
||||
|
||||
now = ->
|
||||
new Date().getTime()
|
||||
|
|
Loading…
Reference in a new issue