ruby-on-rails - Rails API 应用程序中 ActionCable 的 Websocket 客户端

标签 ruby-on-rails websocket ruby-on-rails-5 rails-api actioncable

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

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

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

1:ActionCable usage for Rails API - 这似乎是最好的,但是我怎样才能找到 ActionCable 框架交换的所有 JSON 命令?

2:Similar Question to the mine

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

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

编辑:我也发现了这个 repo action-cable-js但是如何整合呢?

最佳答案

API 的 Actioncable 只有官方支持,还有这个 npm packageactioncable它使用仅使用 API 的方法分离了对与 actioncable 服务器通信的支持。

npm install actioncable
然后在你的 react /角度代码中
import ActionCable from 'actioncable';

# create a connection with the actioncable server
# use ws:// for http and wss:// for https
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);
  }
})

在后端,您需要安装 actioncable,为此请执行此操作
# routes.rb file
Rails.application.routes.draw do
  mount ActionCable.server => '/cable'
end

关于ruby-on-rails - Rails API 应用程序中 ActionCable 的 Websocket 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45784317/

相关文章:

ruby-on-rails - Rails Devise-omniauth 路线指向 passthru 而不是 twitter

ruby-on-rails - 在 Rails + Postgres 中仅附加 jsonb 列

node.js - 如果对等点仍然使用 Nodejs WebRTC 连接,我们将如何在服务器端知道

ruby-on-rails - 如何在 Rails 迁移中限制字符串列的值?

ruby-on-rails - 在 Rails 5 中在哪里添加共享 View 文件?

javascript - 如何在 ruby​​ on Rails 中隐藏 javascript 中的字段?

ruby-on-rails - 在 rails 应用程序中安装 Sinatra 应用程序并共享布局

node.js - RabbitMQ vs Socket.io?

python - 模块未找到错误: No module named 'websocket' even though I installed pip install websocket

mysql - 如何在 Rails 5 迁移中为 MySQL 创建一个 UNSIGNED INT?