ActionCable显示正确的连接用户数(问题:多个选项卡、断开连接)



我是Rails的初学者,正在构建一个问答网络应用程序。目前,我使用ActionCable.server.connections.length来显示有多少人连接到我的测验,但存在多个问题:

  1. 当页面被重新加载一半时ActionCable没有正确断开旧连接,所以这个数字一直在上升,尽管它不应该
  2. 它只为您提供在中调用的特定线程的当前连接数,正如@edwardmp在这条actioncable中指出的那样,如何显示连接的用户线程的数量(这也意味着,为我的应用程序中的一种用户类型的测试主机显示的连接数量可能会因测试参与者显示的连接数量而异)
  3. 当用户连接到多个浏览器窗口时,每个连接都被单独计数,这会错误地增加参与者的数量
  4. 最后但同样重要的是:如果能够显示我频道的每个房间连接的人数,而不是所有房间的连接人数,那就太好了

我注意到,关于这个主题的大多数答案都使用Redis服务器,所以我想知道这是否是我尝试做的事情以及为什么推荐的。(例如,此处:Actioncable连接的用户列表)

我目前使用Devise和Cookie进行身份验证。

对于我的部分问题,任何建议或答案都将不胜感激:)

通过这样做,我终于可以计算服务器上的所有用户(而不是按房间):

我的频道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

现在它起作用了!当用户连接时,计数器递增,当用户关闭窗口或注销时,计数器递减。当用户使用多个选项卡或窗口登录时,这些选项卡或窗口只计数一次。:)

最新更新