defmodule TcpProxy do use GenServer def start_link({watch_pid, to_host, to_port}) do GenServer.start_link(__MODULE__, {watch_pid, to_host, to_port}) end def init({watch_pid, to_host, to_port}) do {:ok, socket} = :gen_tcp.connect(String.to_charlist(to_host), to_port, [:binary, active: true]) {:ok, {watch_pid, socket}} end def handle_info({:tcp, _socket, data}, {watch_pid, _socket} = state) do send(watch_pid, {:send, data}) {:noreply, state} end def handle_info({:send, data}, {watch_pid, socket} = state) do :gen_tcp.send(socket, data) {:noreply, state} end def handle_info({:tcp_closed, _port}, state) do {:stop, :normal, state} end end