使用 ActionCable,有没有办法计算一个频道内有多少订阅者? [英] With ActionCable, is there a way to count how many subscribers from inside a channel?
问题描述
对于我正在构建的应用程序,我有一个大厅"页面,人们可以在其中配置他们想要加入的区域.非常基本.
For an app I'm building, I have a "lobby" page where people configure which area they'd like to join. Pretty basic.
我希望获得当前订阅此页面频道的活跃消费者的总数,以便用户知道周围是否还有其他人可以与之互动.
I'd like to have a running total of active consumers that are currently subscribed to the channel for this page, so that users know whether or not there's other people around to interact with.
有没有简单的方法可以做到这一点?
Is there an easy way to do this?
推荐答案
我定义了一个辅助方法:
I defined a helper method:
app/channels/application_cable/channel.rb
module ApplicationCable
class Channel < ActionCable::Channel::Base
def connections_info
connections_array = []
connection.server.connections.each do |conn|
conn_hash = {}
conn_hash[:current_user] = conn.current_user
conn_hash[:subscriptions_identifiers] = conn.subscriptions.identifiers.map {|k| JSON.parse k}
connections_array << conn_hash
end
connections_array
end
end
end
现在您可以在派生频道内的任何位置调用 connections_info
.该方法返回有关所有可用服务器套接字连接、它们各自的 current_user
及其所有当前订阅的信息性数据数组.
Now you can call connections_info
anywhere inside your derived channel. The method returns an informational array of data about all the available server socket connections, their respective current_user
s and all their current subscriptions.
这是我的数据 connections_info
返回的示例:
Here is an example of my data connections_info
returns:
[1] pry(#<ChatChannel>)> connections_info
=> [{:current_user=>"D8pg2frw5db9PyHzE6Aj8LRf",
:subscriptions_identifiers=>
[{"channel"=>"ChatChannel",
"secret_chat_token"=>"f5a6722dfe04fc883b59922bc99aef4b5ac266af"},
{"channel"=>"AppearanceChannel"}]},
{:current_user=>
#<User id: 2, email: "client1@example.com", created_at: "2017-03-27 13:22:14", updated_at: "2017-04-28 11:13:37", provider: "email", uid: "client1@example.com", first_name: "John", active: nil, last_name: nil, middle_name: nil, email_public: nil, phone: nil, experience: nil, qualification: nil, price: nil, university: nil, faculty: nil, dob_issue: nil, work: nil, staff: nil, dob: nil, balance: nil, online: true>,
:subscriptions_identifiers=>
[{"channel"=>"ChatChannel",
"secret_chat_token"=>"f5a6722dfe04fc883b59922bc99aef4b5ac266af"}]}]
然后您可以按照您想要的方式解析此结构并提取所需的数据.您可以通过相同的current_user
(current_user
方法在class Channel
You can then parse this structure the way you want and extract the desired data. You can distinguish your own connection in this list by the same current_user
(the current_user
method is available inside class Channel < ActionCable::Channel::Base
).
如果用户连接两次(或多次),则对应的数组元素加倍.
If a user connects twice (or more times), then corresponding array elements just double.
这篇关于使用 ActionCable,有没有办法计算一个频道内有多少订阅者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!