如何使用ActionCable作为API

我使用Rails 5 beta 1和ActionCable构建了一个非常简单的应用程序,以显示用户何时联机并让他们相互发送消息。

现在,我基本上想采取ActionCable的客户端部分,在另一个应用程序( 不在 Rails 5上运行)的上下文中实现它并将其与第一个应用程序连接以发送和接收数据(例如在线)用户或消息的状态)。

为了从第二个应用程序发送数据,我认为,我可以简单地发出一个AJAX POST请求。 问题是: 如何从我的第二个应用程序订阅第一个应用程序的开放连接?

甚至:我如何通过API从另一个应用程序订阅我的Rails应用程序的ActionCable连接?

我的猜测是,我基本上想在我的第二个应用程序中以某种方式包含这个coffeescript:

App.appearance = App.cable.subscriptions.create "AppearanceChannel", connected: -> # Called when the subscription is ready for use on the server disconnected: -> # Called when the subscription has been terminated by the server received: (data) -> # ... 

您基本上需要在其他应用程序中包含ActionCable JS代码的副本或端口( https://github.com/rails/rails/tree/master/actioncable/app/assets/javascripts )。

更新:我最近发布了一个名为actioncable-js的npm包,它提供了一个Ruby on Rails 5的ActionCable CofeeScript直接端口到标准JS,以便在Rails之外使用: https : //github.com/mwalsher/actioncable-js

因为ActionCable只是HTML5 WebSockets之上的一个层,所以您还可以使用原始WebSockets JS代码(或任何第三方库)来处理消息传递。

ActionCable消息协议在此处有所记载: https : //github.com/NullVoxPopuli/action_cable_client#the-action-cable-protocol 。 为方便起见,我会在下方粘贴:

  1. 连接到操作电缆URL
  2. 连接成功后,发送订阅消息

    • 订阅消息JSON应如下所示: {"command":"subscribe","identifier":"{\"channel\":\"MeshRelayChannel\"}"}
    • 您应该收到如下消息: {"identifier"=>"{\"channel\":\"MeshRelayChannel\"}", "type"=>"confirm_subscription"}
  3. 订阅后,您可以发送消息。

    • 确保操作字符串与ActionCable服务器上的数据处理方法名称匹配。
    • 您的消息JSON应如下所示: {"command":"message","identifier":"{\"channel\":\"MeshRelayChannel\"}","data":"{\"to\":\"user1\",\"message\":\"hello from user2\",\"action\":\"chat\"}"}
    • 收到的消息应该看起来一样
  4. 笔记:

    • 发送到服务器的每条消息都有一个命令和标识符密钥。
    • 通道值必须与ActionCable服务器上的通道类名称匹配。
    • identifierdata被冗余地jsonified。

所以,例如(在ruby中)

 payload = { command: 'command text', identifier: { channel: 'MeshRelayChannel' }.to_json, data: { to: 'user', message: 'hi', action: 'chat' }.to_json }.to_json 

虽然mwalsher的解决方案对我非常有帮助,但我最近在Rails存储库上找到了拉取请求,并提供了我的问题的官方解决方案。

https://github.com/rails/rails/pull/24991

我假设,在不久的将来,这将被添加到主文档中。 这是官方actioncable npm包的链接: https ://www.npmjs.com/package/actioncable

您可以在任何JS应用程序中使用类似于mwalsher的解决方案。 只需安装npm包:

 npm install actioncable --save 

这里是文档中的JS示例:

 ActionCable = require('actioncable') var cable = ActionCable.createConsumer('wss://RAILS-API-PATH.com/cable') cable.subscriptions.create('AppearanceChannel', { // normal channel code goes here... }); 

编辑:拉取请求已经合并了一段时间,现在,描述是官方自述文件的一部分 – 只是尚未在Rails指南中。