2017-10-11 91 views
0

我是一名Rails初学者构建测验webapp。目前我使用ActionCable.server.connections.length显示有多少人连接到我的测验,但也存在许多问题:ActionCable显示连接用户的正确数量(问题:多个选项卡,断开连接)

  1. 当页面重新加载的时间的一半旧的连接没有断开由ActionCable正确,所以数量不断上升,即使它不应该
  2. 它只会给你指定的线程的当前连接数,这在中被称为@edwardmp指出的this actioncable-how-to-display-number-of-connected-users thread(这也意味着,为测验托管服务器显示的连接(这是我的应用程序中的一种用户类型)可能与显示的连接数不同以测验参与者)
  3. 当用户与多个浏览器窗口,每个连接都seperately计其虚假膨胀参与者
  4. 最后但并非最不重要的数字连接:这将是伟大的,是能够显示每个我的频道的房间连接人数,而不是在所有的房间

我注意到关于这一主题使用Redis的服务器,大多数的答案,所以我想,如果在一般推荐什么我”试图做,为什么。 (例如:Actioncable connected users list

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

任何指针或回答我的问题,甚至部分,将不胜感激:)

回答

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' 
我的频道的

红宝石后端:

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 

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