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) } } 而且你很高兴,在此基础上构建你的逻辑…如果你有任何问题,请告诉我. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |