How to close connection in Action cable?

后端 未结 5 541
时光取名叫无心
时光取名叫无心 2021-01-12 10:59

How to disconnect a client in Action cable (rails 5)? I would like the user to be completely disconnected (similar to when he closes the tab).

5条回答
  •  忘掉有多难
    2021-01-12 11:46

    I found this inside /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.

    Hope this will be useful. Looks like it works even in Rails console.

提交回复
热议问题