Rails API 应用程序中 ActionCable 的 Websocket 客户端

问题描述 投票:0回答:2

我需要在我的 Rails API(仅)应用程序中使用 Websocket。页面没有任何服务器端渲染。该应用程序是 Angular 和 Xamarin 的纯 JSON 后端。我看到很多教程在 Rails 中使用 coffescript 作为 ActionCable 客户端,但这不是我的情况。

问题是:如何在 Rails 的 coffescript 之外将 ActionCable 用作仅 API,例如 Android、iOS、Angular 和 React 客户端?

我发现了不同且有用的资源,但我仍然有点困惑。

1:Rails API 的 ActionCable 用法 - 这似乎是最好的,但是我如何找到 ActionCable 框架交换的所有 JSON 命令?

2:与矿井类似的问题

3:Rails API Websocket GEM - 好吧,不是 ActionCable,但是这个家伙将 coffescript 编译成 JS 并将其移植到项目中。对于移动开发没有用。

如果有不同的解决方案或者更好的知识,请告诉我。我需要“破解”它才能使其正常工作。

编辑:我还发现了这个存储库action-cable-js但是如何集成它?

ruby-on-rails websocket ruby-on-rails-5 rails-api actioncable
2个回答
3
投票

仅适用于 API 的 Actioncable 已获得官方支持,并且有一个名为 actioncable

npm 包
,它为使用仅 API 方法与 Actioncable 服务器进行通信提供了解耦支持。

npm install actioncable

然后在你的反应/角度代码中

import ActionCable from 'actioncable';

# create a connection with the actioncable server
# use ws:// for unencrypted and wss:// for encrypted connection(just like http and https, respectively)
const cable = ActionCable.createConsumer("ws://your-backend-server.com/cable");
# now you create a subscription
my_subscription = cable.subscriptions.create("MessengerChannel", {
  connected: function() {
    console.log("You've subscribed to the Messenger Channel");
  },
  disconnected: function() {
    console.log("You've disconnected from the Messenger Channel");
  },
  received: function (received_data) {
    # broadcast data from the Messenger channel is received here
    console.log(received_data);
  }
})

在后端,您需要安装操作电缆,为此

# routes.rb file
Rails.application.routes.draw do
  mount ActionCable.server => '/cable'
end

2
投票

我希望我的回答对任何人都有用。我终于发现了一个名为 actioncable-js 的库,它在 Angular 项目中为我提供了帮助。

但这还不够。对于移动项目,我需要使用“低级”命令与 Action Cable 服务器交互。

协议在这里:协议

但是如果您需要更多信息,您应该深入了解宝石的内部。

© www.soinside.com 2019 - 2024. All rights reserved.