rails的Action Cable Overview


整体上讲,就是rails项目里面的集成了一个websockets,然后也给客户端提供了一系列的Javascript方法。这样就将web原来的http只能由客户端发起请求 变成了 双方都可以发起请求的websocket(ws, wss)

web上的常规访问,
2个角色:客户,服务器或者broker经纪人
2种方式:客户请求 -- 服务器应答客户发布--服务器broker -- 客户订阅
request response ; publish subscribe
https://blog.opto22.com/optoblog/request-response-vs-pub-sub-part-1

请求-应答


publish-subscribe


Rails的Action Cable集成了websockets的基本的功能,我们只需要在上面写应用层面的逻辑代码就行。

先看概念:
  1. connections:  一个连接就是一个websocket连接(服务器-客户),一个用户可以有多个websocket连接,如果你使用不同的浏览器tab,或者设备。
  2. consumers:  这里的consumer就是连上了websocket的客户。在ActionCable里面这个consumer通过客户端的Javascript来创建。
  3. channnels:  频道channel,只有连上来了,你就会首先订阅了一个频道。你可以同时订阅多个频道。每个频道相当于是MVC里面的C:controller.
  4. subscribers:  客户连上了叫消费者consumers, 消费者订阅了叫订阅者subscribers. 订阅者和频道直接的连接叫:subscription 订阅
  5. pub/sub:   这是一个消息队列的范例。  消息发送方 send data 给一个代表接受者的abstract class ,而不需要单独指定接受者。
  6. broadcastings:  正在广播就是一个 pub/sub 连接。广播的内容都会通过流媒体从广播人直接给频道订阅者。这是正在广播。称呼为广播中的连接可能更合适。每个频道可以streaming多个broadcastings.

Server-side服务器端怎么使用?

每个websockets连接,都是一个连接对象。在这个连接对象的基础上,才有订阅者-频道的连接:subscriptions.


怎么连接?

# app/channels/application_cable/connection.rb
module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      self.current_user = find_verified_user
    end

    private
      def find_verified_user
        if verified_user = User.find_by(id: cookies.encrypted[:user_id])
          verified_user
        else
          reject_unauthorized_connection
        end
      end
  end
end

identified_by 方法:标注一个key作为连接的id,可以用它再次找到特定的连接。通常是current_user, current_account,但不能瞎设置。在channel里有个数组存储这个identifiers,连上后就会加入到这个数组里面。
Note that anything marked as an identifier will automatically create a delegate by the same name on any channel instances created off the connection.这个 created off the connection, 我感觉意思是,离开了connection后创建,

先建立连接connection,这时会有个identifier,然后订阅频道的时候,本频道同名实例会创建一个identifier的委托

reject_unauthorized_connection()
》 Closes the WebSocket connection if it is open and returns a 404 “File not Found” response.


阅读量: 425
发布于:
修改于: