marat
How to disconnect or update Drab socket or channel on user signout
After I built a chat example using the good tutorial (https://tg.pl/drab) and this forum (What is the ~E sigil in the Drab tutorial?) I got into this problem. My application UI is built with React and logout is sent using DELETE /sessions request via ajax.
The controller on the backend processes the request to delete session and this is where the chat channel/socket should get disconnected.
Apparently, I can’t find the way how to disconnect the drab socket.
AppWeb.Endpoint.broadcast!("__drab:global", "disconnect", %{})
AppWeb.Endpoint.broadcast!("__drab:same_path:/", "disconnect", %{})
don’t work.
I’m using
channel "__drab:*", Drab.Channel
def connect(params, socket) do
Drab.Socket.verify(socket, params)
end
in the UserSocket definition, and
{:ok, socket} = connect(UserSocket, %{})
socket.endpoint.broadcast!(socket.id, "disconnect", %{})
doesn’t work as well.
Any clues?
Thanks!
Marked As Solved
OvermindDL1
Also Liked
grych
@OvermindDL1 is right, the best way to disconnect is just to kill the channel (or drab - they are linked). You may get the channel pid from %Phoenix.Socket{}, or drab pid from Drab.pid(socket).
But actually, I have no idea how can I kill socket from the Ajax call in the controller - because this was a question. I mean, which socket shall I kill? You might try to pass the Drab socket to the server, but it is like scratching right ear with the left hand…
Can’t you disconnect using Drab handler? Or - easiest way - just render the page with “normal” way in the controller? You are logging out anyway, so refreshing the whole page is quite normal.
And why do you want to disconnect? Maybe we should start with this.
BTW please do not construct topics like "__drab:same_path:/" yourself. This pattern is private and may change, pls use same_path/1 etc helpers instead.
grych
Nope, this function is not documented, so private. Please don’t use it ![]()
I meant killing the socket with something like
defhandler disconnect(socket, _) do
Process.kill(Drab.pid(socket), :normal)
end
marat
Yeah, that’d be awesome!
So far will stick to @OvermindDL1 recommendation:
OvermindDL1
I kill the entire socket via Phoenix Channel normal disconnect methods.
Drab will then try to reconnect, but if you override the connection event to test a token of your own (that you pass in, it’s documented somewhere) then you can verify that they are not logged in and disallow it, then done. 
/me would normally supply code but is super busy… Maybe @grych can?
OvermindDL1
Broadcasting to __drab:global sounds… not right… I use Endpoint.broadcast("user_socket:" <> user_id, "disconnect", %{}) since I id the sockets to kill the socket itself, not a channel. That’s all normal documented Phoenix Sockets stuff. 







