Joh*_*Del 5 ruby-on-rails websocket ruby-on-rails-5 actioncable
如何使用javascript向所有订阅的websocket连接发送全局消息,而无需通道等(例如,actioncable默认全局发送到所有打开的连接的ping消息)?
据我所知,如果没有通道,你无法直接从 JavaScript 执行此操作(它需要首先通过 Redis)。
我建议您将其作为正常的后期操作执行,然后在 Rails 中发送消息。
我会做这样的事情:
JavaScript:
$.ajax({type: "POST", url: "/notifications", data: {notification: {message: "Hello world"}}})
Run Code Online (Sandbox Code Playgroud)
控制器:
class NotificationsController < ApplicationController
def create
ActionCable.server.broadcast(
"notifications_channel",
message: params[:notification][:message]
)
end
end
Run Code Online (Sandbox Code Playgroud)
渠道:
class NotificationsChannel < ApplicationCable::Channel
def subscribed
stream_from("notifications_channel", coder: ActiveSupport::JSON) do |data|
# data => {message: "Hello world"}
transmit data
end
end
end
Run Code Online (Sandbox Code Playgroud)
听 JavaScript:
App.cable.subscriptions.create(
{channel: "NotificationsChannel"},
{
received: function(json) {
console.log("Received notification: " + JSON.stringify(json))
}
}
)
Run Code Online (Sandbox Code Playgroud)