微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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)
    }

}

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐