From 3e71b4e4841279c74f03cd62ab59c0d46b7bbc57 Mon Sep 17 00:00:00 2001 From: Martin Edenhofer Date: Sat, 4 Aug 2012 15:35:55 +0200 Subject: [PATCH] Added ping connection feature. --- .../javascripts/app/lib/websocket.js.coffee | 31 ++++++++++++++++++- script/websocket-server.rb | 11 +++++-- 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/app/assets/javascripts/app/lib/websocket.js.coffee b/app/assets/javascripts/app/lib/websocket.js.coffee index 5937b5135..3d51fe09b 100644 --- a/app/assets/javascripts/app/lib/websocket.js.coffee +++ b/app/assets/javascripts/app/lib/websocket.js.coffee @@ -7,6 +7,10 @@ class App.WebSocket _instance ?= new _Singleton _instance + @close: (args) -> # Must be a static method + if _instance isnt undefined + _instance.close() + @send: (args) -> # Must be a static method @connect() _instance.send(args) @@ -48,6 +52,24 @@ class _Singleton extends Spine.Controller close: => @ws.close() + ping: => + console.log 'send websockend ping' + @send( { action: 'ping' } ) + + # check if ping is back within 30 sec. + if @check_id + clearTimeout(@check_id) + check = => + console.log 'no websockend ping response, reconnect...' + @close() + @check_id = @delay check, 60000 + + pong: -> + console.log 'received websockend ping' + + # test again after 10 sec. + @delay @ping, 30000 + connect: => # console.log '------------ws connect....--------------' @@ -80,13 +102,20 @@ class _Singleton extends Spine.Controller @send(item) @queue = [] - @ws.onmessage = (e) -> + # send ping to check connection + @delay @ping, 30000 + + @ws.onmessage = (e) => pipe = JSON.parse( e.data ) console.log( "ws:onmessage", pipe ) # go through all blocks for item in pipe + # reset reconnect loop + if item['action'] is 'pong' + @pong() + # fill collection if item['collection'] console.log( "ws:onmessage collection:" + item['collection'] ) diff --git a/script/websocket-server.rb b/script/websocket-server.rb index 10991eaee..89888639a 100644 --- a/script/websocket-server.rb +++ b/script/websocket-server.rb @@ -59,10 +59,12 @@ EventMachine.run { ws.onclose { client_id = ws.object_id puts 'Client ' + client_id.to_s + ' disconnected' - + + # removed from current client list if @clients.include? client_id @clients.delete client_id end + Session.destory( client_id ) } @@ -77,7 +79,12 @@ EventMachine.run { if data['action'] == 'login' @clients[client_id][:session] = data['session'] Session.create( client_id, data['session'] ) - end + + # ping + elsif data['action'] == 'ping' + @clients[client_id][:last_ping] = Time.now + ws.send( '[{"action":"pong"}]' ) + end } end