ruby-on-rails – 一起使用Actioncable和Rails 5 API模式

我正在创建一个非常基本的聊天应用程序我的目标是拥有一个Rails API后端,然后构建一个 IOS,Android,Web和桌面客户端.这纯粹是为了探索Websockets和移动开发.

我从未使用过Actioncable,而且我对Websockets的了解非常有限.我想知道的是,如果我可以在我的Rails API上设置Actioncable并让它与Node通信(例如).

Actioncable的行为与其他任何Websocket一样吗?我可以通过ws://< host> / cable从我的Node应用程序连接到它,并在任何客户端和Rails之间有一个功能性的pub-sub系统吗?

如果这没有意义,我很抱歉,我很难写出来:)

谢谢!

解决方法

的确你可以!

>就像你创建任何api应用程序一样,使用生成

rails new my_app --api

>创建your_channel

rails generate channel your_channel

>在routes.rb中添加装载路径

mount ActionCable.server => '/cable'

>在/app/channels/your_channel.rb中的订阅方法上允许流

class YourChannel < ApplicationCable::Channel

  def subscribed
    stream_from 'messages'        #  <----- Stream Name Here
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end

end

>从应用程序的任何其他部分调用ActionCable.server.broadcast进行流式传输

ActionCable.server.broadcast 'messages',message: 'ping'

>现在使用您的前端进行测试.既然你告诉你想要iOS Android并且还提到了节点,我假设你正在使用(或者会选择使用)react-native

import ActionCable from 'react-native-actioncable';
const cable = ActionCable.createConsumer("ws://localhost:3000/cable");

class YourReactClass extends React.Component {

    # add or update the following

    componentDidMount = () => {
        console.log("componentDidMount executed");
        this.subscription = cable.subscriptions.create("OrderChannel",{
            connected: function() { console.log("connected: action cable") },disconnected: function() { console.log("disconnected: action cable") },received: function (data) { console.log(data) }
            }
        )
    };

    componentwillUnmount () {
        this.subscription &&
        cable.subscriptions.remove(this.subscription)
    }

}

而且你很高兴,在此基础上构建你的逻辑…如果你有任何问题,请告诉我.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...