fxn
Keeping track of WebSocket disconnects
I have a Channels application (WS only) whose clients are phone apps whose source code I control.
The application logs WS connections in the connect/3 callback, but as we know, there is no disconnect callback. I have done some searches and looks like being notified of a disconnection is not trivial (please let me know if I missed any robust solution).
However, in my local tests it seems that a channel’s terminate/2 is called when the socket is closed just fine. I guess that’s possible due to the process structure. Would it be a bad idea to track disconnections this way?
For example, a simple approach could be the following: First thing after connecting, phones would be required to join a dedicated connected channel whose only purpose is to log on join/3 and on terminate/2. Assuming the client code is correct, the join is correctly programmed, and no manual unjoin is coded, do you see drawbacks or better ways to solve this?
Most Liked
LostKobrakai
Given phoenix already comes with a sophisticated solution for tracking presences (Phoenix.Presence) I would just use that one.
sb8244
You can do it by defining your own Phoenix.Socket and implementing init with a track call. I didn’t want to do all of that, and was okay with a warning appearing, so I just defined the function before the use Phoenix.Socket call. pushex/lib/push_ex_web/channels/push_socket.ex at master · pushex-project/pushex · GitHub
That isn’t best practice, but demonstrates how you can track a Socket instead of a Channel. You enter a world of “may not be supported” once you do this, but I think it’s pretty small here.
fxn
This alternative does not issue a warning and it is not coupled to the implementation of the original init/1, only to its return value:
defmodule MyAppWeb.DriverSocket do
use Phoenix.Socket
defoverridable init: 1
def init(state) do
res = {:ok, {_, socket}} = super(state)
MyAppWeb.SocketMonitor.monitor(socket.transport_pid, socket.assigns.driver_id)
res
end
end
kokolegorille
That is exactly what I meant 







