minimart-benchmark-2017/echoserver.erl

51 lines
1.4 KiB
Erlang
Raw Normal View History

2014-05-04 20:36:59 +00:00
-module(echoserver).
-export([start/0]).
start() ->
Port = 5999,
2014-05-05 16:20:07 +00:00
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).
2014-05-04 20:36:59 +00:00
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)
2014-05-05 16:20:07 +00:00
end;
report_stats ->
io:format("~p connections~n", [Count]),
counter(Count)
end.
accept_loop(LSock, CounterPid) ->
2014-05-04 20:36:59 +00:00
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)
2014-05-04 20:36:59 +00:00
end.
connection(Sock, CounterPid) ->
2014-05-04 20:36:59 +00:00
receive
{tcp, _, Line} ->
gen_tcp:send(Sock, Line),
connection(Sock, CounterPid);
2014-05-04 20:36:59 +00:00
{tcp_closed, _} ->
CounterPid ! dec,
2014-05-04 20:36:59 +00:00
ok;
Other ->
error_logger:error_report({connection, unhandled, Other})
end.