36 lines
1.0 KiB
Elixir
36 lines
1.0 KiB
Elixir
defmodule TcpWatcher do
|
|
use GenServer
|
|
|
|
def start_link({to_host, to_port, listen_socket}) do
|
|
GenServer.start_link(__MODULE__, {to_host, to_port, listen_socket})
|
|
end
|
|
|
|
def init({to_host, to_port, listen_socket}) do
|
|
{:ok, {to_host, to_port, listen_socket}, {:continue, :accept}}
|
|
end
|
|
|
|
def handle_continue(:accept, {to_host, to_port, listen_socket} = _state) do
|
|
{:ok, socket} = :gen_tcp.accept(listen_socket)
|
|
start_link({to_host, to_port, listen_socket})
|
|
{:ok, proxy_id} = TcpProxy.start_link({self(), to_host, to_port})
|
|
{:noreply, {to_host, to_port, listen_socket, socket, proxy_id}}
|
|
end
|
|
|
|
def handle_info({:tcp_closed, _socket}, state) do
|
|
{:stop, :normal, state}
|
|
end
|
|
|
|
def handle_info(
|
|
{:tcp, _socket, data},
|
|
{_to_host, _to_port, _listen_socket, _socket, proxy_id} = state
|
|
) do
|
|
send(proxy_id, {:send, data})
|
|
{:noreply, state}
|
|
end
|
|
|
|
def handle_info({:send, data}, {_to_host, _to_port, _listen_socket, socket, _proxy_id} = state) do
|
|
:gen_tcp.send(socket, data)
|
|
{:noreply, state}
|
|
end
|
|
end
|