Skip to content

Instantly share code, notes, and snippets.

@TattdCodeMonkey
Created March 22, 2016 19:58
Show Gist options
  • Save TattdCodeMonkey/945107814ebe31a06236 to your computer and use it in GitHub Desktop.
Save TattdCodeMonkey/945107814ebe31a06236 to your computer and use it in GitHub Desktop.
defmodule TcpUsage do
use GenServer
defmodule State do
defstruct socket: nil
end
def start_link, do: GenServer.start_link(__MODULE__, [])
def init(_) do
# try to open connection in 100ms, this could be a send or cast
Process.send_after(self, :connect, 100)
{:ok, %State{}}
end
def handle_info(:connect, %State{socked: nil} = state) do
{:noreply, connect(state)}
end
def handle_info({:tcp, socket, message}, %State{socket: socket} = state) do
# do something with message
{:noreply, state}
end
def handle_info({:tcp_closed, socket}, %State{socket: socket} = state) do
{:noreply, %{state| socket: nil}
end
defp connect(state) do
opts = [:binary, packet: :line, active: false, reuseaddr: true, keepalive: true]
# I would try to move these to your config, and pass them as args into the genserver,
# Or load them from here with Application.get_env
case :gen_tcp.connect('10.10.10.10', 1000, opts) do
{:ok, socket} ->
%{state| socket: socket}
{:error, _} ->
Process.send_after(self(), :connect, 5_000) # maybe do some backoff here, get the wait time from a function
state
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment