long_polling_controller.rb 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. class LongPollingController < ApplicationController
  2. # GET /api/message_send
  3. def message_send
  4. new_connection = false
  5. # check client id
  6. client_id = client_id_check
  7. if !client_id
  8. new_connection = true
  9. client_id = client_id_gen
  10. puts 'NEW CLIENT CONNECTION: ' + client_id.to_s
  11. else
  12. # cerify client id
  13. if !client_id_verify
  14. render :json => { :error => 'Invalid client_id in send!' }, :status => :unprocessable_entity
  15. return
  16. end
  17. end
  18. if !params['data']
  19. params['data'] = {}
  20. end
  21. # receive message
  22. if params['data']['action'] == 'login'
  23. user_id = session[:user_id]
  24. user = {}
  25. if user_id
  26. user = User.user_data_full( user_id )
  27. end
  28. Session.create( client_id, user, { :type => 'ajax' } )
  29. end
  30. if new_connection
  31. result = { :client_id => client_id }
  32. render :json => result
  33. else
  34. render :json => {}
  35. end
  36. end
  37. # GET /api/message_receive
  38. def message_receive
  39. # check client id
  40. if !client_id_verify
  41. render :json => { :error => 'Invalid client_id receive!' }, :status => :unprocessable_entity
  42. return
  43. end
  44. # check queue queue to send
  45. client_id = client_id_check
  46. begin
  47. count = 28
  48. while true
  49. count = count - 1
  50. queue = Session.queue( client_id )
  51. if queue && queue[0]
  52. # puts "send " + queue.inspect + client_id.to_s
  53. render :json => queue
  54. return
  55. end
  56. sleep 2
  57. if count == 0
  58. render :json => { :action => 'pong' }
  59. return
  60. end
  61. end
  62. rescue
  63. render :json => { :error => 'Invalid client_id in receive loop!' }, :status => :unprocessable_entity
  64. return
  65. end
  66. end
  67. private
  68. def client_id_check
  69. return params[:client_id] if params[:client_id]
  70. return
  71. end
  72. def client_id_gen
  73. rand(99999999)
  74. end
  75. def client_id_verify
  76. return if !params[:client_id]
  77. sessions = Session.sessions
  78. return if !sessions.include?( params[:client_id].to_s )
  79. # Session.update( client_id )
  80. # Session.touch( params[:client_id] )
  81. return true
  82. end
  83. end