获取所有已注册连接的列表

时间:2016-09-29 14:28:56

标签: ruby-on-rails ruby-on-rails-5 actioncable

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

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

这些答案对我没有帮助。

我想获得一个到ActionCable的所有已注册连接的列表。我试过了

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

ActionCable.server.connections.length

但他们都返回[]。所以现在我正在使用像

这样的东西
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

但我知道这完全不是Rails方式。是否有可能获得所有已注册连接的列表?

1 个答案:

答案 0 :(得分:3)

我终于找到了解决方案。

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获取所有服务器连接的列表,但当前连接到套接字的连接除外。这就是为什么你需要直接用ActionCable.server.connections.size + 1

向他发送消息