0

https://stackoverflow.com/a/36230416/5381547

https://stackoverflow.com/a/32945949/5381547

Those answers don't help me.

I want to get a list of all registered connections to my ActionCable. I tried

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

and

ActionCable.server.connections.length,

but they both return []. So for now I'm using something like

def connect
  self.uuid = SecureRandom.uuid

  players_online = REDIS.get('players_online') || 0
  players_online = players_online.to_i
  players_online += 1
  REDIS.set('players_online', players_online)
end

def disconnect
  players_online = REDIS.get('players_online').to_i
  players_online -= 1
  REDIS.set('players_online', players_online)
end

But I know that this is a totally non Rails-way. Is there any possibility to get a list of all registered connections?

Community
  • 1
  • 1
Viktor
  • 4,218
  • 4
  • 32
  • 63

1 Answers1

3

I finally found a solution.

def connect
  self.uuid = SecureRandom.uuid
  transmit({'title': 'players_online', 'message': ActionCable.server.connections.size + 1})
  ActionCable.server.connections.each do |connection|
    connection.transmit({'title': 'players_online', 'message': ActionCable.server.connections.size + 1})
  end
end

def disconnect
  transmit({'title': 'players_online', 'message': ActionCable.server.connections.size})
  ActionCable.server.connections.each do |connection|
    connection.transmit({'title': 'players_online', 'message': ActionCable.server.connections.size})
  end
end

ActionCable.server.connections gets a list of all server connection, except of the one which is currently connecting to the socket. That's why you need to transmit him a message directly with ActionCable.server.connections.size + 1

Viktor
  • 4,218
  • 4
  • 32
  • 63