This commit is contained in:
ydc3148
2026-02-12 12:45:12 +08:00
parent 483675a82f
commit 7811a9ad48
7 changed files with 125 additions and 0 deletions

4
.formatter.exs Normal file
View File

@@ -0,0 +1,4 @@
# Used by "mix format"
[
inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"]
]

24
.gitignore vendored Normal file
View File

@@ -0,0 +1,24 @@
# The directory Mix will write compiled artifacts to.
/_build/
# If you run "mix test --cover", coverage assets end up here.
/cover/
# The directory Mix downloads your dependencies sources to.
/deps/
# Where third-party dependencies like ExDoc output generated docs.
/doc/
# Temporary files, for example, from tests.
/tmp/
# If the VM crashes, it generates a dump, let's ignore it too.
erl_crash.dump
# Also ignore archive artifacts (built via "mix archive.build").
*.ez
# Ignore package tarball (built via "mix hex.build").
alter_proxy-*.tar

39
lib/alter_proxy.ex Normal file
View 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

View 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

29
mix.exs Normal file
View File

@@ -0,0 +1,29 @@
defmodule AlterProxy.MixProject do
use Mix.Project
def project do
[
app: :alter_proxy,
version: "0.1.0",
elixir: "~> 1.19",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger],
mod: {AlterProxy.Application, []}
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
]
end
end

View File

@@ -0,0 +1,8 @@
defmodule AlterProxyTest do
use ExUnit.Case
doctest AlterProxy
test "greets the world" do
assert AlterProxy.hello() == :world
end
end

1
test/test_helper.exs Normal file
View File

@@ -0,0 +1 @@
ExUnit.start()