【问题标题】:ActionCable display correct number of connected users (problems: multiple tabs, disconnects)ActionCable 显示正确的连接用户数(问题:多个选项卡、断开连接)
【发布时间】:2018-03-22 20:03:13
【问题描述】:
我是一名 Rails 初学者,正在构建一个测验 web 应用程序。目前我正在使用ActionCable.server.connections.length 来显示有多少人连接到我的测验,但存在多个问题:
- 当页面重新加载一半时旧的连接没有被 ActionCable 正确断开,所以这个数字一直在上升,即使它不应该
-
它只为您提供调用的特定线程的当前连接数,正如@edwardmp 在this actioncable-how-to-display-number-of-connected-users thread 中指出的那样(这也意味着为测验主机显示的连接数,这是我的应用程序中的一种用户类型,可能与显示给测验参与者的连接数不同)
- 当用户使用多个浏览器窗口进行连接时,每个连接都会单独计算,这会错误地增加参与者的数量
- 最后但并非最不重要的一点:能够显示我的频道的每个房间连接的人数,而不是显示所有房间
我注意到有关此主题的大多数答案都使用 Redis 服务器,所以我想知道这是否通常推荐用于我正在尝试做的事情以及为什么。 (例如这里:Actioncable connected users list)
我目前使用设计和 cookie 进行身份验证。
对我的部分问题的任何指示或答案将不胜感激:)
【问题讨论】:
标签:
ruby-on-rails
ruby
websocket
ruby-on-rails-5
actioncable
【解决方案1】:
通过这样做,我最终至少让它可以计算服务器的所有用户(而不是按房间):
我频道的 CoffeeScript:
App.online_status = App.cable.subscriptions.create "OnlineStatusChannel",
connected: ->
# Called when the subscription is ready for use on the server
#update counter whenever a connection is established
App.online_status.update_students_counter()
disconnected: ->
# Called when the subscription has been terminated by the server
App.cable.subscriptions.remove(this)
@perform 'unsubscribed'
received: (data) ->
# Called when there's incoming data on the websocket for this channel
val = data.counter-1 #-1 since the user who calls this method is also counted, but we only want to count other users
#update "students_counter"-element in view:
$('#students_counter').text(val)
update_students_counter: ->
@perform 'update_students_counter'
我频道的 Ruby 后端:
class OnlineStatusChannel < ApplicationCable::Channel
def subscribed
#stream_from "specific_channel"
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
#update counter whenever a connection closes
ActionCable.server.broadcast(specific_channel, counter: count_unique_connections )
end
def update_students_counter
ActionCable.server.broadcast(specific_channel, counter: count_unique_connections )
end
private:
#Counts all users connected to the ActionCable server
def count_unique_connections
connected_users = []
ActionCable.server.connections.each do |connection|
connected_users.push(connection.current_user.id)
end
return connected_users.uniq.length
end
end
现在它可以工作了!当用户连接时,计数器会增加,当用户关闭窗口或注销时,计数器会减少。当用户使用超过 1 个选项卡或窗口登录时,它们仅计为一次。 :)