【发布时间】:2016-07-23 14:23:49
【问题描述】:
对于我正在构建的应用程序,我有一个“大厅”页面,人们可以在其中配置他们想加入的区域。很基本。
我想统计当前订阅此页面频道的活跃消费者总数,以便用户知道周围是否有其他人可以与之互动。
有没有简单的方法可以做到这一点?
【问题讨论】:
标签: ruby-on-rails-5 actioncable
对于我正在构建的应用程序,我有一个“大厅”页面,人们可以在其中配置他们想加入的区域。很基本。
我想统计当前订阅此页面频道的活跃消费者总数,以便用户知道周围是否有其他人可以与之互动。
有没有简单的方法可以做到这一点?
【问题讨论】:
标签: ruby-on-rails-5 actioncable
我定义了一个辅助方法:
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_users 和它们所有当前订阅的信息数组。
这是我的数据connections_info 返回的示例:
[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 < ActionCable::Channel::Base 中可用)。
如果一个用户连接了两次(或更多次),那么对应的数组元素只会加倍。
【讨论】:
conn.current_user 以nil 的形式返回。
是的,有一个:
在您的应用/频道/what_so_ever_you_call_it.rb 中:
class WhatSoEverYouCalledItChannel < ApplicationCable::Channel
def subscribed
stream_from "your_streamer_thingy"
@subscriber +=1 #<==== like this
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
@subscriber -=1 #<===== like this
end
def send_message(data)
your_message_mechanic
end
设置一个在订阅中增加的变量 并且退订人数减少。
您可能希望将值存储在您的“大厅”模型中,在这种情况下,“@subscriber”可能被称为@lobby.connected_total,我不知道,这符合您的需求。
但这是一种跟踪流数量的方法。
开心
【讨论】: