跳至内容 跳至搜索

Action Cable Server Broadcasting

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 JavaScript, which assumes you've already requested the right to send web notifications:
App.cable.subscriptions.create("WebNotificationsChannel", {
  received: function(data) {
    new Notification(data['title'], { body: data['body'] })
  }
})
命名空间
方法
B

实例公共方法

broadcast(broadcasting, message, coder: ActiveSupport::JSON)

直接将一个哈希广播到一个命名的 broadcasting。稍后它将被 JSON 编码。

# File actioncable/lib/action_cable/server/broadcasting.rb, line 33
def broadcast(broadcasting, message, coder: ActiveSupport::JSON)
  broadcaster_for(broadcasting, coder: coder).broadcast(message)
end

broadcaster_for(broadcasting, coder: ActiveSupport::JSON)

返回一个用于命名 broadcasting 的可重用 broadcaster。当您有一个对象需要一次又一次地将消息发送到特定的 broadcasting 时,这很有用。

# File actioncable/lib/action_cable/server/broadcasting.rb, line 40
def broadcaster_for(broadcasting, coder: ActiveSupport::JSON)
  Broadcaster.new(self, String(broadcasting), coder: coder)
end