2017-10-11 57 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個選項卡或窗口登錄時,它們只計算一次。 :)