我终于至少得到它通过做这一切的用户数到服务器(而不是由室)工作:
的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'
我的频道的
红宝石后端:
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个选项卡或窗口登录时,它们只计算一次。 :)