ruby-on-rails - Rails 5 Actioncable 没有 channel 的全局消息

标签 ruby-on-rails websocket ruby-on-rails-5 actioncable

如何使用javascript向我们所有订阅的websocket连接发送全局消息而无需 channel 等(例如actioncable默认向所有打开的连接全局发送的ping消息)?

最佳答案

据我所知,你不能在没有 channel 的情况下直接从 JavaScript 中做到这一点(它需要先通过 Redis)。

我建议您将其作为正常的发布操作执行,然后在 Rails 中发送消息。

我会做这样的事情:

JavaScript:

$.ajax({type: "POST", url: "/notifications", data: {notification: {message: "Hello world"}}})

Controller :
class NotificationsController < ApplicationController
  def create
    ActionCable.server.broadcast(
      "notifications_channel",
      message: params[:notification][:message]
    )
  end
end

channel :
class NotificationsChannel < ApplicationCable::Channel
  def subscribed
    stream_from("notifications_channel", coder: ActiveSupport::JSON) do |data|
      # data => {message: "Hello world"}
      transmit data
    end
  end
end

听 JavaScript:
App.cable.subscriptions.create(
  {channel: "NotificationsChannel"},
  {
    received: function(json) {
      console.log("Received notification: " + JSON.stringify(json))
    }
  }
)

关于ruby-on-rails - Rails 5 Actioncable 没有 channel 的全局消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48193506/

相关文章:

javascript - 使用 WebSockets 或 WebRTC 发送的数据需要 CRC 吗?

java - 如何保护 Java EE 中的 WebSocket 端点?

ruby-on-rails - Rails 5.1 中的 skip_before_action 回调和继承

ruby-on-rails - 我需要一个 RESTful 实现 RPG 游戏库存 API 的想法

javascript - 使用来自客户端应用程序的 Doorkeeper 进行身份验证而不传输 secret

reactjs - 使用 React Native 在 chrome 开发者工具中查看 websocket 流量

ruby-on-rails - 我收到此错误 : NoMethodError at . .. 未定义的方法

ruby-on-rails - Skip_callbacks - 不工作 Rails 5

ruby-on-rails - rake db :migrate and rake db:create both work on test database, 不是开发数据库

mysql - 从多个嵌套记录加载记录的复杂查询