Action Cable 服务器广播
Broadcasting
是应用程序的其他部分向频道订阅者发送消息的方式。如 Channel
中所述,大多数情况下,这些广播会直接流式传输给订阅了指定广播的客户端。我们通过一个全栈示例进行说明
class WebNotificationsChannel < ApplicationCable::Channel
def subscribed
stream_from "web_notifications_#{current_user.id}"
end
end
# Somewhere in your app this is called, perhaps from a NewCommentJob:
ActionCable.server.broadcast \
"web_notifications_1", { title: "New things!", body: "All that's fit for print" }
# Client-side CoffeeScript, which assumes you've already requested the right to send web notifications:
App.cable.subscriptions.create "WebNotificationsChannel",
received: (data) ->
new Notification data['title'], body: data['body']
命名空间
方法
实例公共方法
broadcast(broadcasting, message, coder: ActiveSupport::JSON) 链接
将哈希直接广播到指定 broadcasting
。稍后会对哈希进行 JSON 编码。
来源:显示 | 在 GitHub 上
# File actioncable/lib/action_cable/server/broadcasting.rb, line 26 def broadcast(broadcasting, message, coder: ActiveSupport::JSON) broadcaster_for(broadcasting, coder: coder).broadcast(message) end
broadcaster_for(broadcasting, coder: ActiveSupport::JSON) 链接
返回一个用于指定 broadcasting
的广播器,该广播器可以重复使用。当您有一个对象可能需要多个位置来反复传输到特定广播时,这很有用。
来源:显示 | 在 GitHub 上
# File actioncable/lib/action_cable/server/broadcasting.rb, line 32 def broadcaster_for(broadcasting, coder: ActiveSupport::JSON) Broadcaster.new(self, String(broadcasting), coder: coder) end