<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                企業??AI智能體構建引擎,智能編排和調試,一鍵部署,支持知識庫和私有化部署方案 廣告
                # 7. actioncable 入門 #### 1. 介紹 websocket的序列文章重點要講的就是[actioncable](https://github.com/rails/rails/tree/master/actioncable),之前也講了好多關于各種方式實現聊天室的文章,相信從中,也能學到好多關于websocket實踐的知識和經驗,這節要來講講actioncable。 actioncable是集成在rails 5中的一個功能,它能夠輕易的在rails中使用websocket。現在先把actioncable用起來,再慢慢研究其原理和特性。 #### 2. 使用 還是跟先前的例子一樣,建立一個聊天室。 ##### 2.1 聊天室界面 首先,rails的版本必須得是5以上,寫這篇文章的時候,rails 5正式版還沒有出來,目前的版本是5.0.0.beta4。 ``` $ rails new actioncable_demo $ cd actioncable_demo ``` 這樣就生成了一個新項目。 接著創建message這個model,存儲聊天記錄。 ``` $ rails g model message content:text $ rails db:migrate ``` 創建聊天室的界面。 在config/routes.rb中添加路由。 ``` Rails.application.routes.draw do get 'rooms/show' end ``` 創建controller,添加`app/controllers/rooms_controller.rb`文件,內容如下: ``` class RoomsController < ApplicationController def show @messages = Message.all end end ``` 添加view,添加`app/views/rooms/show.html.erb`文件,內容如下: ``` <h1>Chat room</h1> <div id="messages"> <%= render @messages %> </div> <form> <label>Say something:</label><br> <input type="text" data-behavior="room_speaker"> </form> ``` 還有`app/views/messages/_message.html.erb`文件,內容如下: ``` <div class=“message”> <p><%= message.content %></p> </div> ``` 到目前為止,按照之前的經驗,界面都建立好了,如下圖所示: ![](https://box.kancloud.cn/8cca60ba03748f4f5a895f71a6826c6e_379x225.png) ##### 2.2 開啟websocket 接下來,就是要來處理websocket部分。 先在客戶端瀏覽器中開啟websocket請求。 actioncable默認提供了一個文件`app/assets/javascripts/cable.coffee`,把幾行注釋打開,就可以開啟websocket,內容如下: ``` # #= require action_cable #= require_self #= require_tree ./channels # @App ||= {} App.cable = ActionCable.createConsumer() ``` 其實這些js的內容很簡單,它做的主要的事情就是前面幾篇文章所講的在客戶端瀏覽器執行`new WebSocket`,具體的內容可以查看其源碼。 還要在路由中添加下面這行,把websocket服務以engine的方式掛載起來。 ``` mount ActionCable.server => '/cable' ``` 至此,websocket已經開啟了,可以通過chrome瀏覽器的開發者工具查看鏈接的信息,只要有101協議的信息,表示就是成功的。 ![](https://box.kancloud.cn/c8d0274c8f9fb60e0acf5389d890d68f_973x204.png) ##### 2.3 channel 現在要讓客戶端和服務器端連接起來。 actioncable提供了一個叫做`channel`的技術,中文名可以稱為`"通道"`。actioncable是一種`pub/sub`的架構,服務器通過channel發布消息,多個客戶端通過對應的channel訂閱消息,服務器能夠廣播消息給客戶端,從而實現客戶端和服務器端的交互。 先新建一個channel。 ``` $ rails g channel room speak ``` 修改`app/channels/room_channel.rb`文件,內容如下: ``` class RoomChannel < ApplicationCable::Channel def subscribed stream_from "room_channel" end def unsubscribed # Any cleanup needed when channel is unsubscribed end def speak(data) # ActionCable.server.broadcast "room_channel", message: data['message'] Message.create! content: data['message'] end end ``` 其中定義了三個方法,分別是`subscribed`,`unsubscribed`,`speak`。 `subscribed`和`unsubscribed`方法是默認就生成的,而`speak`是我們自己定義的。 `subscribed`表示的是當客戶端連接上來的時候使用的方法。 `unsubscribed`表示的是當客戶端與服務器失去連接的時候使用的方法。 還有,`app/assets/javascripts/channels/room.coffee`文件,內容如下: ``` App.room = App.cable.subscriptions.create "RoomChannel", connected: -> # Called when the subscription is ready for use on the server disconnected: -> # Called when the subscription has been terminated by the server received: (data) -> $('#messages').append data['message'] # Called when there's incoming data on the websocket for this channel speak: (message) -> @perform 'speak', message: message $(document).on 'keypress', '[data-behavior~=room_speaker]', (event) -> if event.keyCode is 13 # return = send App.room.speak event.target.value event.target.value = "" event.preventDefault() ``` `App.room`里定義了四個方法,除了`speak`,`connected`、`disconnected`、`received`都是actioncable定義的。 這幾個方法可以和`RoomChannel`里的方法對應起來,比如: `connected`和`subscribed`對應,表示客戶端和服務器端連接之后的情況。 `disconnected`和`unsubscribed`對應,表示客戶端和服務器端失去連接之后的情況。 `received`表示從服務器接收到信息之后的情況。因為服務器總是要向客戶端推送信息的,接收完信息之后,就可以在這里進行一些頁面上的操作,比如DOM更新等。 `room.coffee`文件中有重要的一行`App.room.speak event.target.value`,當鍵入聊天信息,一按回車鍵后,就會通過這行代碼,把聊天信息,發送到后端服務器,并且會被`room_channel.rb`中的`speak`接收,執行`Message.create! content: data['message']`命令。 ##### 2.4 activejob 現在還沒真正完成,還差一部分。 `room.coffee`文件中有一個`received`方法,它有一行指令`$('#messages').append data['message']`。 這個表示當聊天信息發出時,會在聊天信息展示界面上添加聊天的內容。 現在來處理這個,我們通過activejob來處理,還記得之前的`app/views/messages/_message.html.erb`文件嗎,現在要發揮它的作用。 先建立一個job。 ``` $ rails g job message_broadcast ``` 修改`app/jobs/message_broadcast_job.rb`文件,內容如下: ``` class MessageBroadcastJob < ApplicationJob queue_as :default def perform(message) ActionCable.server.broadcast 'room_channel', message: render_message(message) end private def render_message(message) ApplicationController.renderer.render(partial: 'messages/message', locals: { message: message }) end end ``` 還要在一個地方執行這個job,是當創建完message的時候。 修改`app/models/message.rb`文件,內容如下: ``` class Message < ApplicationRecord after_create_commit { MessageBroadcastJob.perform_later self } end ``` 做完這一切,重啟一下服務器。 現在來看下效果: ![](https://box.kancloud.cn/16588ee53a535517b39a3ee5ba4c2437_799x306.png) 本篇完結。 下一篇: [websocket之actioncable進階(八)](http://www.rails365.net/articles/websocket-zhi-actioncable-jin-jie-ba)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看