Kie*_*n E 5 ruby-on-rails websocket node.js actioncable
我正在创建一个非常基本的聊天应用程序 我的目标是拥有一个Rails API后端,然后构建一个IOS,Android,Web和桌面客户端.这纯粹是为了探索Websockets和移动开发.
我从未使用过Actioncable,而且我对Websockets的了解非常有限.我想知道的是,如果我可以在我的Rails API上设置Actioncable并让它与Node通信(例如).
Actioncable的行为与其他任何Websocket一样吗?我可以从我的Node应用程序连接到它,ws://<host>/cable并在任何客户端和Rails之间有一个功能的pub-sub系统吗?
如果这没有意义,我很抱歉,我很难写出来:)
谢谢!
的确你可以!
就像你创建任何api应用程序一样,使用生成器
rails new my_app --api
Run Code Online (Sandbox Code Playgroud)创建your_channel
rails generate channel your_channel
Run Code Online (Sandbox Code Playgroud)添加挂载路径 routes.rb
mount ActionCable.server => '/cable'
Run Code Online (Sandbox Code Playgroud)在订阅方法中允许流 /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
Run Code Online (Sandbox Code Playgroud)ActionCable.server.broadcast从您应用的任何其他部分拨打电话进行通话
ActionCable.server.broadcast 'messages', message: 'ping'
Run Code Online (Sandbox Code Playgroud)现在用你的前端来测试它.既然你告诉你想要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)
}
}
Run Code Online (Sandbox Code Playgroud)你很高兴,在此基础上构建你的逻辑......如果你遇到任何问题,请告诉我.
| 归档时间: |
|
| 查看次数: |
896 次 |
| 最近记录: |