ActionCable显示正确数量的已连接用户(问题:多个选项卡,断开连接)

时间:2017-10-11 08:21:11

标签: ruby-on-rails ruby websocket ruby-on-rails-5 actioncable

我是一名Rails初学者,正在构建一个测验webapp。目前,我使用ActionCable.server.connections.length来显示有多少人与我的测验相关联,但存在多个问题:

  1. 当页面重新加载时,ActionCable的一半时间旧连接未正确断开,因此即使不应该
  2. ,数字也会不断上升
  3. 它只为你提供中调用的特定线程的当前连接数,正如this actioncable-how-to-display-number-of-connected-users thread中指出的@edwardmp(这也意味着显示的连接数)对于测验主机,我的应用程序中的一种用户,可以从显示给测验参与者的连接数量不等)
  4. 当用户使用多个浏览器窗口连接时,每个连接都会单独计算,这会错误地增加参与者数量
  5. 最后但并非最不重要:能够显示我的频道的每个房间连接的人数,而不是所有房间
  6. 会很棒

    我注意到有关此主题的大多数答案都使用Redis服务器,所以我想知道这是否通常建议用于我尝试做什么以及为什么。 (例如:Actioncable connected users list

    我目前使用Devise和Cookie进行身份验证。

    对我的部分问题的任何指示或答案都将不胜感激:)

1 个答案:

答案 0 :(得分:0)

我最终通过这样做至少可以将所有用户计入服务器(而不是按房间):

我频道的CoffeeScript:

App.online_status = App.cable.subscriptions.create "OnlineStatusChannel",
  connected: ->
    # Called when the subscription is ready for use on the server
    #update counter whenever a connection is established
    App.online_status.update_students_counter()

  disconnected: ->
    # Called when the subscription has been terminated by the server
    App.cable.subscriptions.remove(this)
    @perform 'unsubscribed'

  received: (data) ->
    # Called when there's incoming data on the websocket for this channel
    val = data.counter-1 #-1 since the user who calls this method is also counted, but we only want to count other users
    #update "students_counter"-element in view:
    $('#students_counter').text(val)

  update_students_counter: ->
    @perform 'update_students_counter'

我的频道的Ruby后端:

class OnlineStatusChannel < ApplicationCable::Channel
  def subscribed
    #stream_from "specific_channel"
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
    #update counter whenever a connection closes
    ActionCable.server.broadcast(specific_channel, counter: count_unique_connections )
  end

  def update_students_counter
    ActionCable.server.broadcast(specific_channel, counter: count_unique_connections )
  end

  private:
  #Counts all users connected to the ActionCable server
  def count_unique_connections
    connected_users = []
    ActionCable.server.connections.each do |connection|
      connected_users.push(connection.current_user.id)
    end
    return connected_users.uniq.length
  end
end

现在它有效!当用户连接时,计数器递增,当用户关闭窗口或注销时,计数器递减。当用户使用多个选项卡或窗口登录时,它们只计算一次。 :)