ActionCable - how to display number of connected users? ActionCable - how to display number of connected users? ruby-on-rails ruby-on-rails

ActionCable - how to display number of connected users?


Seems that one way is to use

ActionCable.server.connections.length

(See caveats in the comments)


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.rbmodule 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  endend

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']   endend


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.