This commit is contained in:
2026-02-19 10:14:42 +08:00
parent 9d91a77647
commit f1cde528a4
6 changed files with 78 additions and 107 deletions

35
lib/tcp_watcher.ex Normal file
View File

@@ -0,0 +1,35 @@
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