From c768f02f573a599a853ebfd0475f8c05bae4679a Mon Sep 17 00:00:00 2001 From: Martin Edenhofer Date: Tue, 27 Nov 2012 01:59:46 +0100 Subject: [PATCH] Added broadcast feature to long polling. --- app/controllers/long_polling_controller.rb | 22 ++++++++++++++++++++++ script/websocket-server.rb | 20 +++++++++++++++----- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/app/controllers/long_polling_controller.rb b/app/controllers/long_polling_controller.rb index 0e024a71e..12938a3ec 100644 --- a/app/controllers/long_polling_controller.rb +++ b/app/controllers/long_polling_controller.rb @@ -29,6 +29,28 @@ class LongPollingController < ApplicationController user = User.user_data_full( user_id ) end Session.create( client_id, user, { :type => 'ajax' } ) + + # broadcast + elsif params['data']['action'] == 'broadcast' + + # list all current clients + client_list = Session.list + client_list.each {|local_client_id, local_client| + if local_client_id != client_id + + # broadcast to recipient list + if params['data']['recipient'] && params['data']['recipient']['user_id'] + params['data']['recipient']['user_id'].each { |user_id| + if local_client[:user][:id] == user_id + Session.send( local_client_id, params['data'] ) + end + } + # broadcast every client + else + Session.send( local_client_id, params['data'] ) + end + end + } end if new_connection diff --git a/script/websocket-server.rb b/script/websocket-server.rb index 4863f35c2..0c0ed6662 100644 --- a/script/websocket-server.rb +++ b/script/websocket-server.rb @@ -140,21 +140,31 @@ EventMachine.run { elsif data['action'] == 'broadcast' # list all current clients - @clients.each { |local_client_id, local_client| + client_list = Session.list + client_list.each {|local_client_id, local_client| if local_client_id != client_id # broadcast to recipient list if data['recipient'] && data['recipient']['user_id'] data['recipient']['user_id'].each { |user_id| - if local_client[:session]['id'] == user_id + if local_client[:user][:id] == user_id log 'notice', "send broadcast to (user_id=#{user_id})", local_client_id - local_client[:websocket].send( "[#{msg}]" ) + if local_client[:meta][:type] == 'websocket' && @clients[ local_client_id ] + @clients[ local_client_id ][:websocket].send( "[#{msg}]" ) + else + Session.send( local_client_id, data ) + end end } + # broadcast every client else log 'notice', "send broadcast", local_client_id - local_client[:websocket].send( "[#{msg}]" ) + if local_client[:meta][:type] == 'websocket' && @clients[ local_client_id ] + @clients[ local_client_id ][:websocket].send( "[#{msg}]" ) + else + Session.send( local_client_id, data ) + end end end } @@ -162,7 +172,7 @@ EventMachine.run { } end - # check open unused connections, kick all connection without activitie in the last 5 minutes + # check open unused connections, kick all connection without activitie in the last 2 minutes EventMachine.add_periodic_timer(120) { log 'notice', "check unused idle connections..."