相关疑难解决方法(0)

ActionCable - 如何显示已连接用户的数量?

我正在尝试使用Action Cable创建一个简单的类似聊天的应用程序(计划扑克应用程序).我对术语,文件层次结构以及回调的工作方式感到有些困惑.

这是创建用户会话的操作:

class SessionsController < ApplicationController
  def create
    cookies.signed[:username] = params[:session][:username]
    redirect_to votes_path
  end
end
Run Code Online (Sandbox Code Playgroud)

然后,用户可以发布应该向所有人广播的投票:

class VotesController < ApplicationController
  def create
    ActionCable.server.broadcast 'poker',
                                 vote: params[:vote][:body],
                                 username: cookies.signed[:username]
    head :ok
  end
end
Run Code Online (Sandbox Code Playgroud)

到目前为止,一切都很清楚,并且工作正常.问题是 - 如何显示已连接用户的数量?当用户(消费者?)连接时,JS中是否会触发回调?我想要的是当我在隐身模式下在3个不同浏览器中打开3个标签时,我想显示"3".当新用户连接时,我希望该数字递增.如果任何用户断开连接,则该号码应减少.

我的PokerChannel:

class PokerChannel < ApplicationCable::Channel
  def subscribed
    stream_from 'poker'
  end
end
Run Code Online (Sandbox Code Playgroud)

app/assets/javascripts/poker.coffee:

App.poker = App.cable.subscriptions.create 'PokerChannel',

  received: (data) ->
    $('#votes').append @renderMessage(data)

  renderMessage: (data) ->
    "<p><b>[#{data.username}]:</b> #{data.vote}</p>"
Run Code Online (Sandbox Code Playgroud)

ruby-on-rails websocket actioncable

15
推荐指数
1
解决办法
5595
查看次数

Actioncable连接用户列表

我在ActionCable中验证用户是这样的:

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      self.current_user = find_verified_user
      logger.add_tags 'ActionCable', current_user.name
    end

    protected
      def find_verified_user
        if verified_user = User.find_by(id: cookies.signed[:user_id])
          verified_user
        else
          reject_unauthorized_connection
        end
      end
  end
end
Run Code Online (Sandbox Code Playgroud)

是否有可能获得连接用户列表?我用谷歌搜索,但发现只有这个stackoverflow问题:第一,第二

ruby ruby-on-rails websocket actioncable

2
推荐指数
1
解决办法
1971
查看次数

标签 统计

actioncable ×2

ruby-on-rails ×2

websocket ×2

ruby ×1