我終於至少得到它通過做這一切的用戶數到服務器(而不是由室)工作:
的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個選項卡或窗口登錄時,它們只計算一次。 :)