43 lines
1.4 KiB
Erlang
43 lines
1.4 KiB
Erlang
%%%-------------------------------------------------------------------
|
|
%%% @author anlicheng
|
|
%%% @copyright (C) 2025, <COMPANY>
|
|
%%% @doc
|
|
%%%
|
|
%%% @end
|
|
%%% Created : 29. 4月 2025 23:24
|
|
%%%-------------------------------------------------------------------
|
|
-module(efka_tcp_server).
|
|
-author("anlicheng").
|
|
|
|
%% API
|
|
-export([start_link/1, init/1]).
|
|
|
|
start_link(Port) ->
|
|
{ok, spawn_link(?MODULE, init, [Port])}.
|
|
|
|
%% 监听循环
|
|
init(Port) ->
|
|
case gen_tcp:listen(Port, [binary, {packet, 4}, {active, false}, {reuseaddr, true}]) of
|
|
{ok, ListenSocket} ->
|
|
efka_logger:debug("Server started on port ~p~n", [Port]),
|
|
main_loop(ListenSocket);
|
|
{error, Reason} ->
|
|
efka_logger:debug("Failed to start server: ~p~n", [Reason]),
|
|
exit(Reason)
|
|
end.
|
|
|
|
main_loop(ListenSocket) ->
|
|
case gen_tcp:accept(ListenSocket) of
|
|
{ok, Socket} ->
|
|
% 为每个新连接生成一个处理进程
|
|
{ok, ChannelPid} = efka_tcp_sup:start_child(Socket),
|
|
ok = gen_tcp:controlling_process(Socket, ChannelPid),
|
|
% 继续监听下一个连接
|
|
main_loop(ListenSocket);
|
|
{error, closed} ->
|
|
efka_logger:debug("Server socket closed~n", []),
|
|
exit(tcp_closed);
|
|
{error, Reason} ->
|
|
efka_logger:debug("Accept error: ~p~n", [Reason]),
|
|
exit(Reason)
|
|
end. |