fixup
This commit is contained in:
39
lib/alter_proxy.ex
Normal file
39
lib/alter_proxy.ex
Normal file
@@ -0,0 +1,39 @@
|
||||
defmodule AlterProxy do
|
||||
def start(port) do
|
||||
# 監聽端口
|
||||
{:ok, listen_socket} =
|
||||
:gen_tcp.listen(port, [
|
||||
:binary,
|
||||
packet: :line,
|
||||
reuseaddr: true,
|
||||
active: false,
|
||||
backlog: 100
|
||||
])
|
||||
|
||||
accept_loop(listen_socket)
|
||||
end
|
||||
|
||||
defp accept_loop(listen_socket) do
|
||||
{:ok, socket} = :gen_tcp.accept(listen_socket)
|
||||
|
||||
# 爲每個客戶端創建新進程處理
|
||||
spawn(__MODULE__, :handle_client, [socket])
|
||||
|
||||
# 繼續等待下一個連接
|
||||
accept_loop(listen_socket)
|
||||
end
|
||||
|
||||
def handle_client(socket) do
|
||||
# 接收數據
|
||||
case :gen_tcp.recv(socket, 0) do
|
||||
{:ok, data} ->
|
||||
IO.puts("收到: #{data}")
|
||||
:gen_tcp.send(socket, "Echo: #{data}")
|
||||
# 繼續接收
|
||||
handle_client(socket)
|
||||
|
||||
{:error, :closed} ->
|
||||
IO.puts("客戶端斷開連接")
|
||||
end
|
||||
end
|
||||
end
|
||||
20
lib/alter_proxy/application.ex
Normal file
20
lib/alter_proxy/application.ex
Normal file
@@ -0,0 +1,20 @@
|
||||
defmodule AlterProxy.Application do
|
||||
# See https://hexdocs.pm/elixir/Application.html
|
||||
# for more information on OTP Applications
|
||||
@moduledoc false
|
||||
|
||||
use Application
|
||||
|
||||
@impl true
|
||||
def start(_type, _args) do
|
||||
children = [
|
||||
# Starts a worker by calling: AlterProxy.Worker.start_link(arg)
|
||||
# {AlterProxy.Worker, arg}
|
||||
]
|
||||
|
||||
# See https://hexdocs.pm/elixir/Supervisor.html
|
||||
# for other strategies and supported options
|
||||
opts = [strategy: :one_for_one, name: AlterProxy.Supervisor]
|
||||
Supervisor.start_link(children, opts)
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user