2016-05-18 51 views
1

我用戶進行身份驗證ActionCable這樣的:Actioncable連接的用戶列表

module ApplicationCable 
    class Connection < ActionCable::Connection::Base 
    identified_by :current_user 

    def connect 
     self.current_user = find_verified_user 
     logger.add_tags 'ActionCable', current_user.name 
    end 

    protected 
     def find_verified_user 
     if verified_user = User.find_by(id: cookies.signed[:user_id]) 
      verified_user 
     else 
      reject_unauthorized_connection 
     end 
     end 
    end 
end 

是否有可能獲得連接的用戶列表?我谷歌搜索,但只發現這個計算器的問題:first,second

回答

6

雅有點必須推出自己的用戶跟蹤。

重要的位如下:

# connection 
module ApplicationCable 
    class Connection < ActionCable::Connection::Base 
    identified_by :uid 

    def connect 
     self.uid = get_connecting_uid 
     logger.add_tags 'ActionCable', uid 
    end 

    protected 

    # the connection URL to this actioncable/channel must be 
    # domain.tld?uid=the_uid 
    def get_connecting_uid 
     # this is just how I get the user id, you can keep using cookies, 
     # but because this key gets used for redis, I'd 
     # identify_by the user_id instead of the current_user object 
     request.params[:uid] 
    end 
    end 
end 


# Your Channel 
def subscribed 
    stop_all_streams 
    stream_from broadcasting_name 
    ConnectedList.add(uid) 
end 

def unsubscribed 
    ConnectedList.remove(uid) 
end 

然後在模型:

class ConnectedList 
    REDIS_KEY = 'connected_nodes' 

    def self.redis 
    @redis ||= ::Redis.new(url: ActionCableConfig[:url]) 
    end 

    # I think this is the method you want. 
    def self.all 
    redis.smembers(REDIS_KEY) 
    end 

    def self.clear_all 
    redis.del(REDIS_KEY) 
    end 

    def self.add(uid) 
    redis.sadd(REDIS_KEY, uid) 
    end 

    def self.include?(uid) 
    redis.sismember(REDIS_KEY, uid) 
    end 

    def self.remove(uid) 
    redis.srem(REDIS_KEY, uid) 
    end 
end 

來自:https://github.com/NullVoxPopuli/mesh-relay/

+0

看來,重啓作用電纜服務器時,connected_nodes不會重啓。任何解決方法? – cisolarix

+0

可能會添加一個初始化程序來清除redis緩存connected_nodes? – NullVoxPopuli

+1

我相信當一個特定用戶連接多個瀏覽器窗口時,這也會失敗。當用戶關閉一個窗口時,即使它們仍然從另一個窗口連接,它們將從ConnectedList中完成刪除(因爲用戶列表是使用一個集合進行跟蹤的)。 – odonnellt