How to close connection in Action cable?

后端 未结 5 486
时光取名叫无心
时光取名叫无心 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

    Disconnecting a client from your rails application

    If you want to disconnect a client from the rails application, use the disconnect method as described in the documentation: 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
    

    Disconnecting from the client side

    If you want to disconnect the user from the client side you can use the disconnect and unsubscribe functions in your javascript:

    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();
    

提交回复
热议问题