Consuming Rails 5 ActionCable

随声附和 提交于 2019-12-01 13:06:16

问题


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?

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.

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


回答1:


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

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

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

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\"}"');
  });
}

Reference: http://edgeguides.rubyonrails.org/action_cable_overview.html#channels

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



来源:https://stackoverflow.com/questions/39185275/consuming-rails-5-actioncable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!