Created
March 22, 2016 19:58
-
-
Save TattdCodeMonkey/945107814ebe31a06236 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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