消费 Rails 5 ActionCable [英] Consuming Rails 5 ActionCable

查看:48
本文介绍了消费 Rails 5 ActionCable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试新的 ActionCable 功能.有没有办法使用 socket.io 或使用 React 或 ReactNative 的应用程序与 ActionCable 服务器进行通信?

I'm playing around with the new ActionCable feature. Is there a way of communicating with the ActionCable server using say socket.io or from an application using React or ReactNative?

也许我混淆了 ActionCable 的正确使用,它不打算用作 API 替代品,它旨在用作同一应用程序的支持前端技术.

Perhaps I'm confusing the correct use of ActionCable and it is not intended to be used as a let's say API replacement and it is meant to be used as a supporting front end technology for the same app.

如果可能,将不胜感激任何使用 ActionCable 作为独立 WS 服务器的好的示例或指南.

Any good example or guide to use ActionCable as standalone WS server would be appreciated if this is possible.

推荐答案

您可以像通常与任何 WebSocket 库一样与 ActionCable 进行交互.

You can interact with ActionCable as you would normally with any WebSocket libraries.

为此,您将从 Rails 中的 Channel 流式传输:

To do so, you would stream from a Channel in Rails:

class ExampleChannel < ApplicationCable::Channel
  def subscribe
    stream_from 'example'
  end
end

然后,您可以通过独立客户端连接到 Rails WebSocket 并使用 ActionCable 协议订阅消息:

Then, you may connect to the Rails WebSocket through your stand-alone client and subscribe to the message using the ActionCable protocol:

function Socket(url) {
  const ws = new WebSocket(url);

  ws.onopen(() => {
    ws.send('{"command":"subscribe","identifier":"{\"channel\":\"ExampleChannel\"}"');
  });
}

参考:http://edgeguides.rubyonrails.org/action_cable_overview.html#channels

https://github.com/NullVoxPopuli/action_cable_client/blob/master/README.md

这篇关于消费 Rails 5 ActionCable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆