How to close connection in Action cable?

浪子不回头ぞ 提交于 2019-12-05 12:59:15

You can use the unsubscribe() function:

App.example = App.cable.subscriptions.create(..);
App.example.unsubscribe();

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.

Disconnecting from the client

I stumbled across this issue too. But I could not believe that there is no simple way to disconnect the websocket connection from the client (without doing an API call). Luckily this works for me:

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

to disconnect from the client side (in js), call

App.cable.disconnect();

to disconnect from the server side - see the answer from @prograils

My work around was to create a new route just for disconnect.

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

   render json: {}, status: 200 
end

The client side would have to call the endpoint... something like

PUT  /api/cable/disconnection
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!