Action Cable 连接基础
对于 Action Cable 服务器接受的每个 WebSocket 连接,都会实例化一个 Connection
对象。此实例将成为从此处创建的所有频道订阅的父级。然后,传入消息将根据 Action Cable 消费者发送的标识符路由到这些频道订阅。 Connection
本身不会处理除身份验证和授权之外的任何特定应用程序逻辑。
这是一个基本示例
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
self.current_user = find_verified_user
logger.add_tags current_user.name
end
def disconnect
# Any cleanup work needed when the cable connection is cut.
end
private
def find_verified_user
User.find_by_identity(cookies.encrypted[:identity_id]) ||
reject_unauthorized_connection
end
end
end
首先,我们声明此连接可以通过其 current_user 进行标识。这使我们能够在以后找到为该 current_user 建立的所有连接(并可能断开这些连接)。您可以声明任意数量的标识索引。声明标识意味着会自动为此键设置 attr_accessor。
其次,我们依赖于这样一个事实,即 WebSocket 连接是通过发送沿域的 Cookie 建立的。这使得使用在通过 Web 界面登录时设置的签名 Cookie 来授权 WebSocket 连接变得很容易。
最后,我们使用当前用户的名称向特定于连接的记录器添加一个标签,以便在日志中轻松区分其消息。
相当简单,对吧?
方法
- B
- C
- H
- N
- R
- S
包含的模块
- ActionCable::Connection::Identification
- ActionCable::Connection::InternalChannel
- ActionCable::Connection::Authorization
- ActionCable::Connection::Callbacks
- ActiveSupport::Rescuable
属性
[R] | env | |
[R] | logger | |
[R] | protocol | |
[R] | server | |
[R] | subscriptions | |
[R] | worker_pool |
类公共方法
new(server, env, coder: ActiveSupport::JSON) 链接
# File actioncable/lib/action_cable/connection/base.rb, line 58 def initialize(server, env, coder: ActiveSupport::JSON) @server, @env, @coder = server, env, coder @worker_pool = server.worker_pool @logger = new_tagged_logger @websocket = ActionCable::Connection::WebSocket.new(env, self, event_loop) @subscriptions = ActionCable::Connection::Subscriptions.new(self) @message_buffer = ActionCable::Connection::MessageBuffer.new(self) @_internal_subscriptions = nil @started_at = Time.now end
实例公共方法
beat() 链接
close(reason: nil, reconnect: true) 链接
关闭 WebSocket 连接。
handle_channel_command(payload) 链接
send_async(method, *arguments) 链接
通过线程工作池异步调用连接上的方法。
statistics() 链接
返回一个基本统计信息哈希,其中包含以 identifier
、started_at
、subscriptions
和 request_id
为键的连接。健康检查可以返回此信息。
实例私有方法
request() 链接
初始化 WebSocket 连接的请求在此处可用。这可以访问环境、cookie 等。
来源:显示 | 在 GitHub 上
# File actioncable/lib/action_cable/connection/base.rb, line 164 def request # :doc: @request ||= begin environment = Rails.application.env_config.merge(env) if defined?(Rails.application) && Rails.application ActionDispatch::Request.new(environment || env) end end