如何关闭动作电缆中的连接?

How to close connection in Action cable?

如何在Action cable(rails5)中断开客户端? 我希望用户完全断开连接(类似于他关闭选项卡时)。

正在断开客户端与您的 rails 应用程序的连接

如果要断开客户端与 rails 应用程序的连接,请使用文档中所述的 disconnect 方法: https://api.rubyonrails.org/classes/ActionCable/RemoteConnections.html

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user
    ....
  end
end

ActionCable.server.remote_connections.where(current_user: User.find(1)).disconnect

正在与客户端断开连接

如果您想断开用户与客户端的连接,您可以在 javascript:

中使用 disconnectunsubscribe 函数
App.cable = ActionCable.createConsumer(...)

// Closes the websocket connection.
App.cable.disconnect();

// Unsubscribe from a actioncable subscription (without disconnecting the websocket connection)
App.example = App.cable.subscriptions.create(..);
App.example.unsubscribe();

我在 /var/lib/gems/2.3.0/gems/actioncable-5.0.1/lib/action_cable/remote_connections.rb

中找到了这个

If you need to disconnect a given connection, you can go through the RemoteConnections. You can find the connections you're looking for by searching for the identifier declared on the connection. For example:

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user
    ....
  end
end

ActionCable.server.remote_connections.where(current_user: User.find(1)).disconnect

This will disconnect all the connections established for
User.find(1), across all servers running on all machines, because it uses the internal channel that all of these servers are subscribed to.

希望这会有用。看起来它甚至在 Rails 控制台中也能正常工作。

我的解决方法是为断开连接创建一条新路由。

def disconnection
    ActionCable.server.remote_connections.where(connected_user: user_params['email']).disconnect

   render json: {}, status: 200 
end

客户端必须调用端点...类似于

PUT  /api/cable/disconnection

正在与客户端断开连接

我也偶然发现了这个问题。但我不敢相信没有简单的方法可以断开客户端的 websocket 连接(不进行 API 调用)。幸运的是这对我有用:

// Create consumer
window.cable = ActionCable.createConsumer(...)

// Subscribe to channels
window.cable.subscriptions.create('SomeChannel', ...);

// At some point we want to disconnect (e.g. when user logs out)
window.cable.subscriptions.consumer.disconnect();

要与客户端断开连接(在 js 中),请调用

App.cable.disconnect();

从服务器端断开连接 - 请参阅@prograils

的回答

正在关闭来自 channel

的所有 websocket 连接
connection.close

正在从客户端退订

App.cable.disconnect();

正在与外界断开连接connection/channel

ActionCable.server.remote_connections.where(current_user: User.find(params[:id])).disconnect