我使用 Rails 5 beta 1 和 ActionCable 构建了一个非常简单的应用程序,用于显示用户何时上线并让他们互相发送消息。
现在,我基本上想采用 ActionCable 的客户端部分,在另一个应用程序的上下文中实现它(这确实not在Rails 5上运行)并将其与第一个应用程序连接以发送和接收数据(例如用户的在线状态或消息)。
我认为,要从第二个应用程序发送数据,我可以简单地发出 AJAX POST 请求。问题是:如何从第二个应用程序订阅第一个应用程序的开放连接?
甚至:如何通过 API 从另一个应用程序订阅我的 Rails 应用程序的 ActionCable 连接?
我的猜测是,我本质上想以某种方式在我的第二个应用程序中包含这个咖啡脚本:
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 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 https://github.com/mwalsher/actioncable-js
由于 ActionCable 只是 HTML5 WebSockets 之上的一层,因此您还可以使用原始 WebSockets JS 代码(或任何第三方库)来处理消息传递。
ActionCable 消息协议在此处有所记录:https://github.com/NullVoxPopuli/action_cable_client#the-action-cable-protocol https://github.com/NullVoxPopuli/action_cable_client#the-action-cable-protocol。为了方便起见,我将粘贴在下面:
- 连接到操作电缆 URL
-
连接成功后,发送订阅消息
- 订阅消息 JSON 应如下所示:
{"command":"subscribe","identifier":"{\"channel\":\"MeshRelayChannel\"}"}
- 您应该收到如下消息:
{"identifier"=>"{\"channel\":\"MeshRelayChannel\"}", "type"=>"confirm_subscription"}
-
订阅后,您可以发送消息。
- 确保操作字符串与 ActionCable 服务器上的数据处理方法名称匹配。
- 您的消息 JSON 应如下所示:
{"command":"message","identifier":"{\"channel\":\"MeshRelayChannel\"}","data":"{\"to\":\"user1\",\"message\":\"hello from user2\",\"action\":\"chat\"}"}
- 收到的消息应该看起来差不多
-
Notes:
- 发送到服务器的每条消息都有一个命令和标识符密钥。
- 通道值必须与 ActionCable 服务器上通道类的名称匹配。
-
identifier
and data
被冗余地json化了。
例如(在红宝石中)
payload = {
command: 'command text',
identifier: { channel: 'MeshRelayChannel' }.to_json,
data: { to: 'user', message: 'hi', action: 'chat' }.to_json
}.to_json
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)