A TCP server in depth

In Erlang a socket that serves one request and stops is a test fixture. A server accepts connections for as long as it runs, and every connection needs its own process: a client that sends slowly, or not at all, must not stop the next client from being accepted. The sockets lesson shows the calls on one connection; this lesson builds the loop around them, and the two mistakes that come with it.

An accept loop and a handler

The acceptor is one process that does nothing but accept. For each connection it starts a handler, hands the socket over, and returns to gen_tcp:accept/2. The handover is gen_tcp:controlling_process/2: the socket has one owner, the process that receives its messages and may close it, and this call moves that ownership. The program below also counts the connections, and it accepts with a timeout so that the same process can answer a question between two connections:

echo_srv.erl

-module(echo_srv). -export([main/0]). main() -> {ok, Listen} = gen_tcp:listen(0, [binary, {packet, line}, {active, false}, {reuseaddr, true}]), {ok, Port} = inet:port(Listen), Server = spawn_link(fun() -> accept_loop(Listen, 0) end), First = round_trip(Port, <<"one\n">>), Second = round_trip(Port, <<"two\n">>), io:format("echo 1: ~p~n", [First]), io:format("echo 2: ~p~n", [Second]), Server ! {stats, self()}, receive {stats, Count} -> io:format("handled: ~p~n", [Count]) end. round_trip(Port, Line) -> {ok, Client} = gen_tcp:connect({127, 0, 0, 1}, Port, [binary, {packet, line}, {active, false}]), ok = gen_tcp:send(Client, Line), {ok, Echo} = gen_tcp:recv(Client, 0, 1000), ok = gen_tcp:close(Client), Echo. accept_loop(Listen, Count) -> case gen_tcp:accept(Listen, 100) of {ok, Socket} -> start_handler(Socket), accept_loop(Listen, Count + 1); {error, timeout} -> check_mailbox(Listen, Count) end. check_mailbox(Listen, Count) -> receive {stats, From} -> From ! {stats, Count}, accept_loop(Listen, Count) after 0 -> accept_loop(Listen, Count) end. start_handler(Socket) -> Handler = spawn_link(fun() -> wait_for_socket() end), ok = gen_tcp:controlling_process(Socket, Handler), Handler ! {socket, Socket}. wait_for_socket() -> receive {socket, Socket} -> ok = inet:setopts(Socket, [{active, once}]), handler(Socket) end. handler(Socket) -> receive {tcp, Socket, Line} -> ok = gen_tcp:send(Socket, Line), ok = inet:setopts(Socket, [{active, once}]), handler(Socket); {tcp_closed, Socket} -> ok end.

erlc echo_srv.erl

erl -noshell -eval 'echo_srv:main(), halt().'

echo 1: <<"one\n">> echo 2: <<"two\n">> handled: 2

Two connections, two handler processes, one acceptor. The handler is passive until it owns the socket, then it asks for one message at a time with {active, once}: each message turns the mode off again, and the handler sets it for the next one after it has done the work. That is flow control by construction, and it is why a handler that writes to a slow client never builds a queue of unread messages.

Who owns the socket

The mistake this design punishes is a handler that skips the handover. Any process may call inet:setopts/2 on a socket, and the call succeeds, but the messages go to the process that owns the socket, not to the one that asked. A handler that never became the owner waits for a message that was delivered elsewhere:

wrong_owner.erl

-module(wrong_owner). -export([main/0]). main() -> {ok, Listen} = gen_tcp:listen(0, [binary, {packet, line}, {active, false}]), {ok, Port} = inet:port(Listen), {ok, Client} = gen_tcp:connect({127, 0, 0, 1}, Port, [binary, {packet, line}, {active, false}]), {ok, Server} = gen_tcp:accept(Listen, 1000), spawn_link(fun() -> handler(Server, self()) end), ok = gen_tcp:send(Client, <<"hello\n">>), receive {tcp, _Socket, Line} -> io:format("owner: ~p~n", [Line]) after 300 -> io:format("owner: nothing~n") end, receive handler_done -> ok after 500 -> ok end, ok = gen_tcp:close(Client), ok = gen_tcp:close(Server), ok = gen_tcp:close(Listen). handler(Socket, Parent) -> ok = inet:setopts(Socket, [{active, once}]), receive {tcp, Socket, Line} -> io:format("handler: ~p~n", [Line]) after 200 -> io:format("handler: nothing~n") end, Parent ! handler_done.

erlc wrong_owner.erl

erl -noshell -eval 'wrong_owner:main(), halt().'

owner: <<"hello\n">> handler: nothing

The handler set the mode and waited, and the line went to the owner. The fix is one call before the handler is told about the socket, and it must come from the owner: gen_tcp:controlling_process(Socket, Handler). The order matters too: transfer the socket first, then send the message that tells the handler to start, or the handler may read a socket it does not own yet.

Active N

{active, true} sends every message as it arrives, with no limit; {active, once} sends exactly one and waits for the process to ask again; {active, N} sends at most N and then stops by itself. That last form is the practical middle: a batch of messages per round trip, and the runtime holds the rest in the socket buffer instead of the mailbox. This program sends three lines and sets the counter to two:

flow.erl

-module(flow). -export([main/0]). main() -> {ok, Listen} = gen_tcp:listen(0, [binary, {packet, line}, {active, false}]), {ok, Port} = inet:port(Listen), {ok, Client} = gen_tcp:connect({127, 0, 0, 1}, Port, [binary, {packet, line}, {active, false}]), {ok, Server} = gen_tcp:accept(Listen, 1000), [ok = gen_tcp:send(Client, Line) || Line <- [<<"one\n">>, <<"two\n">>, <<"three\n">>]], ok = inet:setopts(Server, [{active, 2}]), io:format("with active 2: ~p~n", [count(Server)]), ok = inet:setopts(Server, [{active, 2}]), io:format("after a second call: ~p~n", [count(Server)]), ok = gen_tcp:close(Client), ok = gen_tcp:close(Server), ok = gen_tcp:close(Listen). count(Socket) -> receive {tcp, Socket, _Line} -> 1 + count(Socket) after 100 -> 0 end.

erlc flow.erl

erl -noshell -eval 'flow:main(), halt().'

with active 2: 2 after a second call: 1

Two messages arrived and the mode turned itself off, so the third line stayed in the socket until the next call asked for more. A server that sets {active, true} and then does something slow is the opposite case: the mailbox grows with whatever the client sends, and the memory of the node grows with it. The processes in depth lesson reads message_queue_len to see that happen.

The shape of a server

The pieces above are the whole of a TCP server, and a real one is the same pieces in a supervision tree. The listening socket is opened once, by a child that owns it for the life of the node, and the acceptor is a supervised process that restarts if it crashes. Each handler is started under a supervisor whose strategy is simple_one_for_one or a dynamic child of a one_for_one tree, so a handler that crashes takes only its own connection with it. The capstone TCP server puts the pieces together with a table of live sockets, and the supervision trees lesson gives the tree its shape.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Why does every connection get its own handler process?

    Answer

    A slow client must not stop the next accept

    The acceptor returns to accept at once, and one quiet client cannot hold up the others.

  2. What does gen_tcp:controlling_process/2 do?

    Answer

    Moves the ownership of the socket to another process

    The owner receives the socket messages and may close it, so the handover is what makes a handler work.

  3. Which process receives a socket message after inet:setopts/2 sets an active mode?

    Answer

    The owner of the socket

    The call succeeds from any process, but the messages go to the owner alone.

  4. What does {active, N} do after N messages?

    Answer

    It turns itself off and waits for another call

    The counter runs down to zero and the socket becomes passive, which is the flow control the owner asked for.

  5. Why is {active, true} dangerous for a slow handler?

    Answer

    Every message the client sends lands in the mailbox

    Nothing limits the messages, so the memory of the process grows with the traffic.

  6. What does gen_tcp:accept(Listen, 100) answer when no client arrives?

    Answer

    {error, timeout}

    The timeout is a normal answer, and it is what lets the acceptor check its mailbox.

  7. What does this module print? -module(q1). -export([main/0]). main() -> {ok, Listen} = gen_tcp:listen(0, [binary, {packet, line}, {active, false}]), {ok, Port} = inet:port(Listen), {ok, Client} = gen_tcp:connect({127, 0, 0, 1}, Port, [binary, {packet, line}, {active, false}]), {ok, Server} = gen_tcp:accept(Listen, 1000), ok = gen_tcp:send(Client, <<"alpha\nbeta\n">>), R1 = gen_tcp:recv(Server, 0, 1000), R2 = gen_tcp:recv(Server, 0, 1000), io:format("~p~n", [R1]), io:format("~p~n", [R2]).

    Answer

    {ok,<<"alpha\n">>} / {ok,<<"beta\n">>}

    Line mode gives one message per line, so each read answers one line.

  8. What does this module print? -module(q2). -export([main/0]). main() -> {ok, Listen} = gen_tcp:listen(0, [binary, {packet, line}, {active, false}]), {ok, Port} = inet:port(Listen), {ok, Client} = gen_tcp:connect({127, 0, 0, 1}, Port, [binary, {packet, line}, {active, false}]), {ok, Server} = gen_tcp:accept(Listen, 1000), ok = inet:setopts(Server, [{active, once}]), ok = gen_tcp:send(Client, <<"one\n">>), R = receive {tcp, Server, Line} -> Line after 200 -> nothing end, io:format("~p~n", [R]).

    Answer

    <<"one\n">>

    The process that accepted the socket owns it, so it receives the message the active mode delivers.

  9. What does this module print? -module(q3). -export([main/0]). main() -> {ok, Listen} = gen_tcp:listen(0, [binary, {packet, line}, {active, false}]), {ok, Port} = inet:port(Listen), {ok, Client} = gen_tcp:connect({127, 0, 0, 1}, Port, [binary, {packet, line}, {active, false}]), {ok, Server} = gen_tcp:accept(Listen, 1000), ok = inet:setopts(Server, [{active, 1}]), ok = gen_tcp:send(Client, <<"a\n">>), ok = gen_tcp:send(Client, <<"b\n">>), R1 = receive {tcp, Server, Line} -> Line after 200 -> nothing end, R2 = receive {tcp, Server, Line2} -> Line2 after 200 -> nothing end, io:format("~p~n", [{R1, R2}]).

    Answer

    {<<"a\n">>,nothing}

    One message is delivered and the mode turns off, so the second line stays in the socket.

  10. What does this module print? -module(q4). -export([main/0]). main() -> {ok, Listen} = gen_tcp:listen(0, [binary, {packet, line}, {active, false}]), {ok, Port} = inet:port(Listen), {ok, Client} = gen_tcp:connect({127, 0, 0, 1}, Port, [binary, {packet, line}, {active, false}]), {ok, Server} = gen_tcp:accept(Listen, 1000), ok = gen_tcp:close(Client), R = gen_tcp:recv(Server, 0, 200), io:format("~p~n", [R]).

    Answer

    {error,closed}

    The client closed the connection, so the server read reports closed.

The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Автор статьи: Arthur Isaev