ActionCable - how to display number of connected users?

五迷三道 提交于 2019-11-27 21:25:18
pmichna

Seems that one way is to use

ActionCable.server.connections.length

(See caveats in the comments)

In a related question on who is connected, there was an answer for those who uses redis:

Redis.new.pubsub("channels", "action_cable/*")

and if you just want number of connections:

Redis.new.pubsub("NUMPAT", "action_cable/*")

This will summarize connections from all your servers.

All the magic covered inside RemoteConnections class and InternalChannel module.

TL;DR all connections subscibed on special channels with a prefix action_cable/* with only purpose of disconnecting sockets from main rails app.

For a quick (and probably not ideal) solution you can write a module that tracks subscription counts (using Redis to store data):

#app/lib/subscriber_tracker.rb
module SubscriberTracker
  #add a subscriber to a Chat rooms channel 
  def self.add_sub(room)
    count = sub_count(room)
    $redis.set(room, count + 1)
  end

  def self.remove_sub(room)
    count = sub_count(room)
    if count == 1
      $redis.del(room)
    else
      $redis.set(room, count - 1)
    end
  end

  def self.sub_count(room)
    $redis.get(room).to_i
  end
end

And update your subscribed and unsubscribed methods in the channel class:

class ChatRoomsChannel < ApplicationCable::Channel  
  def subscribed
     SubscriberTracker.add_sub params['room_id']
  end

  def unsubscribed
     SubscriberTracker.remove_sub params['chat_room_id'] 
  end
end

With

ActionCable.server.pubsub.send(:listener).instance_variable_get("@subscribers")

you can get map with subscription identifier in the key and array of procedures which will be executed on the broadcast. All procedures accept message as argument and have memoized connection.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!