Send message to `Phoenix.Socket` process (not to the client, but elixir process)

Hello,
I am trying to implement an auto-disconnect feature for my websocket.

My first idea would is to approach the websocket (module having use Phoenix.Socket) as a regular GenServer and just use Process.send_after/3 inside of connect/3 referring to current socket’s process with self/0 like so:

defmodule MySuperWeb.UserSocket do
  use Phoenix.Socket
  
  @impl true
  def connect(params, socket, connect_info) do
    Process.send_after(self(), :session_timeout, 30_000)
    
    {:ok, socket}
  end
  
  @impl true
  def handle_info(:session_timeout, socket) do
    {:stop, :normal, socket}
  end
end

But this does not seem to do anything and it even gives me warnings that the handle_info/2 already defined in Phoenix.Socket already matches… so this is not feasible…

Of course I could create another GenServer that would do this kind of thing, that is, if I have access to correct PID with self/0 inside connect/3 (something like ProcessMurderer.murder_self_after/1 :slight_smile:)

Thanks for help or guidance.

:wave:

Maybe something like this would work:

defmodule MySuperWeb.UserSocket do
  use Phoenix.Socket
  
  @impl true
  def connect(_params, socket, _connect_info) do
    #  or :socket_drain
    Process.send_after(self(), %Phoenix.Socket.Broadcast{event: "disconnect"}, :timer.seconds(30))
    {:ok, socket}
  end
end

Context: phoenix/lib/phoenix/socket.ex at e2ec5e09bc6ade8ba60bf9582362dbd911e055f1 · phoenixframework/phoenix · GitHub

1 Like

Hello,
Thanks. That will probably be it. I will try this as soon as I get to the PC.

PS: I feel bad for not thinking about looking a level deeper… :slight_smile: