tcp connection manager in elixir

This might be a common pattern so in general this is how it can be done the main thing is to use
timer for reconnection
handle_info callback to detect when the socket goes down
port_info function for status check

1. open connection in init function
2. add reconnection try function each 10 sec
3. add handle_info callback that will recieve message once socket gets closed

defmodule ConnectionManager do
  use GenServer

  # Callbacks
  def init()do
    #initial connect
    {:ok, sock} = :gen_tcp.connect(someHostInNet, 5678, 
                                 [:binary, {:packet, 0}])
    
    {:ok, [sock]}
  end
  def handle_call(:reconnectTry, _from, state) do
    if reconnect(state)==:failed do
      :timer.apply_after(10000,GenServer,:call,[self(),:reconnectTry])
    end
    {:noreply, state}
  end
  def reconnect(state)do
     [socket]=state

     result=:erlang.port_info(socket,:connected)
     if result==:undefined do
        #reconnect
     end
  end
  def handle_info({:tcp_closed, socket}, state) do
    #try to reconnect right away once we get message it is closed
    if reconnect(state)==:failed do
      :timer.apply_after(10000,GenServer,:call,[self(),:reconnectTry])
    end
    {:noreply, state}
  end
end

Leave a Comment