3

没有太多关于动作电缆的文档,所以我对此有点迷茫。我正在使用 rails 5 应用程序,我正在尝试将 rails5 应用程序用作纯粹的 api 并将我的 JS 托管在其他地方。所以当我启动我的 actioncable 服务器时,我可以很容易地连接到 websocket,只需使用我内置的浏览器套接字支持:

var socket = new WebSocket('localhost:3000/cable')
// and then do
socket.onmessage = function(data) { console.log(data) }

我连接成功。我收到以下形式的 ping

MessageEvent {isTrusted: true, data: "{"type":"ping","message":1462992407}", ... etc

除了我似乎无法向客户端广播任何消息。我试过了:

ActionCable.server.broadcast('test',{ yes: true })

但只有 ping 进来。ActionCable 有它自己的概念,我还没有完全理解这些概念,比如频道和在 Rails 应用程序中“正常工作”的东西。但是如何使用 actioncable 的套接字服务器成功构建一个单独的独立 JS 应用程序?

4

1 回答 1

0

我将 ActionCable 与 iOS 应用程序一起使用。一切正常。

ActionCable 使用发布/订阅模式。

Pub/Sub 或 Publish-Subscribe 指的是一种消息队列范式,其中信息的发送者(发布者)将数据发送到抽象类的接收者(订阅者),而不指定单个接收者。Action Cable 使用这种方法在服务器和许多客户端之间进行通信。

这意味着您应该首先创建一个新频道,

rails g channel my_channel

然后在您的频道中发送一些测试消息:

# app/channels/my_channel.rb
class MyChannel < ApplicationCable::Channel
  def subscribed
    stream_from "my_channel"
    ActionCable.server.broadcast "my_channel", 'Test message'
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end
end

然后将以下内容发送到您的服务器:

{'command': 'subscribe', 'identifier': {\'channel\':\'MyChannel\'}}

作为回报,您将获得第一帧。

于 2016-10-27T16:10:53.263 回答