2016-11-18 22 views
4

我正在創建一個非常基本的聊天應用程序。我的目標是擁有一個Rails API後端,然後構建一個IOS,Android,Web和桌面客戶端。這純粹是爲了探索Websockets和移動開發。一起使用Actioncable和Rails 5 API模式

我從來沒有使用過Actioncable,而且我對Websockets的知識非常有限。我想知道的是,如果我可以在Rails API上設置Actioncable並使其與Node進行通信(例如)。

Actioncable是否像其他任何Websocket一樣行事?我可以通過ws://<host>/cable從Node應用程序連接到它,並且在任何客戶端和Rails之間都有一個可用的pub-sub系統?

對不起,如果是沒有意義的,我有一個很難措辭吧:)

謝謝!

+0

我現在想知道同樣的事情。想辦法? –

+0

看看這個:https://github.com/rails/rails/issues/22669 –

回答

6

確實可以!

  1. 就像您創建的任何API的應用程序,使用發電機

    rails new my_app --api 
    
  2. 創建your_channel

    rails generate channel your_channel 
    
  3. 添加安裝路徑routes.rb

    mount ActionCable.server => '/cable' 
    
  4. 允許在訂閱方法流/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 
    
  5. 呼叫ActionCable.server.broadcast從您的應用程序的任何其他部分以流

    ActionCable.server.broadcast 'messages', message: 'ping' 
    
  6. 現在使用您的前端進行測試。既然你說你想要的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) 
        } 
    
    } 
    

,你是好去,在建立自己的邏輯頂部...如果您有任何問題,請告訴我。