51 lines
1.4 KiB
Erlang
51 lines
1.4 KiB
Erlang
-module(echoserver).
|
|
|
|
-export([start/0]).
|
|
|
|
start() ->
|
|
Port = 5999,
|
|
CounterPid = spawn(fun () ->
|
|
timer:send_interval(2000, report_stats),
|
|
counter(0)
|
|
end),
|
|
{ok, LSock} = gen_tcp:listen(Port, [{active, true}, {packet, line}, {reuseaddr, true}]),
|
|
io:format("Erlang echo server running on port ~p.~n", [Port]),
|
|
accept_loop(LSock, CounterPid).
|
|
|
|
counter(Count) ->
|
|
receive
|
|
inc ->
|
|
counter(Count + 1);
|
|
dec ->
|
|
case Count - 1 of
|
|
0 ->
|
|
io:format("Exiting on zero connection count.~n"),
|
|
init:stop();
|
|
NewCount ->
|
|
counter(NewCount)
|
|
end;
|
|
report_stats ->
|
|
io:format("~p connections~n", [Count]),
|
|
counter(Count)
|
|
end.
|
|
|
|
accept_loop(LSock, CounterPid) ->
|
|
case gen_tcp:accept(LSock) of
|
|
{ok, Sock} ->
|
|
CounterPid ! inc,
|
|
gen_tcp:controlling_process(Sock, spawn(fun () -> connection(Sock, CounterPid) end)),
|
|
accept_loop(LSock, CounterPid)
|
|
end.
|
|
|
|
connection(Sock, CounterPid) ->
|
|
receive
|
|
{tcp, _, Line} ->
|
|
gen_tcp:send(Sock, Line),
|
|
connection(Sock, CounterPid);
|
|
{tcp_closed, _} ->
|
|
CounterPid ! dec,
|
|
ok;
|
|
Other ->
|
|
error_logger:error_report({connection, unhandled, Other})
|
|
end.
|