【问题标题】:Rails ActionCable unsubscribe users when browser close浏览器关闭时,Rails ActionCable 取消订阅用户
【发布时间】:2018-01-26 22:47:04
【问题描述】:

我正在用一个非常简单的例子来测试 ActionCable。 我想查看一个网站上一次连接了多少用户。 用户未在系统中注册。 用户被分配了一个带有 uuid 的会话变量。 为了使示例尽可能简单,我没有包含模型或数据库。

#app/controller/users_controller.rb

class UsersController < ApplicationController 

  def index
    if session[:user].nil?
      session[:user] = SecureRandom.uuid
    end
    @user = session[:user]
    UserBroadcastJob.perform_later @user
    end
  end

视图很简单

#app/views/users/index.html.erb

<h1>Users</h1>

<div id="users">
  <%= render "user",user: @user %>
</div>

部分用户:

#app/views/users/_user.html.erb

<div class="user">
  User : <%= user %>
</div>

我用job调用socket

#app/jobs/user_broadcast_job.rb

class UserBroadcastJob < ApplicationJob
queue_as :default

  def perform(user)
    ActionCable.server.broadcast 'user_channel', message: render_user(user)
  end

  def render_user(user)
    ApplicationController.renderer.render(partial: 'users/user', locals: { user: user })
  end
end

还有频道

App.user = App.cable.subscriptions.create "UserChannel",
connected: ->

disconnected: ->

received: (data) ->
console.log(data)
$("#users").prepend(data.message)

这可以正常工作。在我打开的每个浏览器中,连接的 uuid 都是可见的。 由于我不使用数据库进行持久性,因此第一个打开的浏览器具有所有 uuid,其余浏览器变为 n-1 uuid 可见。这不重要。

我的问题是:

如果浏览器关闭,我如何发送消息从模板中删除 uuid?

ActionCable 不适用于会话。

Ruby 版本:2.4.0 导轨版本:5.1.3 通过 yarn 安装 jquery

谢谢!!!!

【问题讨论】:

    标签: ruby-on-rails ruby actioncable


    【解决方案1】:

    您可以在

    下执行此操作
      def unsubscribed
        # Any cleanup needed when channel is unsubscribed
      end
    

    在您的频道/application_cable/your_channel.rb 中

    此外,ActionCable does work with sessions,不过需要进行一些调整。

    如果您对测试 ActionCable 的并发性认真(即认真考虑在高档生产中使用 ActionCable),我建议您已经放弃并使用插件 anyCable .将为您节省大量时间。

    【讨论】:

      【解决方案2】:

      对你很有帮助

      class AppearanceChannel < ApplicationCable::Channel
        def subscribed
          stream_from "appearance"
          @current_user = User.find(params[:room])
          @current_user.appear
          ActionCable.server.broadcast('appearance',{data: @current_user.appear,action: 'SubscribedList'})
        end
      
        def unsubscribed
          if @current_user.present? 
            ActionCable.server.broadcast('appearance',{data: @current_user.disappear,action: 'SubscribedList'})
          end
        end
      
      end
      

      您可以传递参数来订阅,但取消订阅是不可能的参数。所以当你调用订阅时将 current_user 存储到一个变量中,并说要在取消订阅端销毁我。

      【讨论】:

      • 值得一提的是params 不能与unsubscribed 一起使用,谢谢!
      猜你喜欢
      • 2016-12-25
      • 1970-01-01
      • 2018-06-14
      • 2019-04-27
      • 2020-02-14
      • 1970-01-01
      • 2017-09-28
      • 1970-01-01
      • 2017-11-12
      相关资源
      最近更新 更多