Capstone: TCP server

The second capstone is a server: several clients, one line from each, and every line reaching all of them. It is the program the sockets lesson prepares and the TCP server in depth takes further, and its shape is the classic one of Erlang: a listening socket, one acceptor process, one handler process per client, and a table of the live sockets.

A listener and one client

Start with the smallest complete pair: a listener on port 0, one client in another process, and one line each way. Port 0 lets the kernel pick a free port, and inet:port/1 reports the number, so a test never clashes with a port that is in use. The program prints what the client received at each step:

echo.erl

-module(echo). -export([main/0]). main() -> {ok, Listen} = gen_tcp:listen(0, [binary, {packet, line}, {active, false}, {reuseaddr, true}]), {ok, Port} = inet:port(Listen), Self = self(), spawn_link(fun() -> client(Port, Self) end), {ok, Socket} = gen_tcp:accept(Listen), ok = gen_tcp:send(Socket, "welcome\n"), {ok, Line} = gen_tcp:recv(Socket, 0, 1000), ok = gen_tcp:send(Socket, Line), ok = gen_tcp:close(Socket), ok = gen_tcp:close(Listen), receive {client, Reply} -> io:format("client read: ~p~n", [Reply]) end. client(Port, Parent) -> {ok, Socket} = gen_tcp:connect({127, 0, 0, 1}, Port, [binary, {packet, line}, {active, false}]), {ok, Welcome} = gen_tcp:recv(Socket, 0, 1000), ok = gen_tcp:send(Socket, "hello\n"), {ok, Echo} = gen_tcp:recv(Socket, 0, 1000), ok = gen_tcp:close(Socket), Parent ! {client, {Welcome, Echo}}.

erlc echo.erl

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

client read: {<<"welcome\n">>,<<"hello\n">>}

{packet, line} makes the socket deliver whole lines, so a recv never returns half a message. {active, false} keeps the data in the socket until the process asks, which is the mode to reason about first; the in depth lesson switches to {active, once} when a process must also serve other messages.

A server for many clients

The chat server keeps an acceptor that only accepts, a handler per client that only reads, and an ETS table of the sockets that every handler can reach. The program starts the server, joins two clients, sends one line from the first and checks that both received it:

chat.erl

-module(chat). -export([main/0]). main() -> {ok, Listen} = gen_tcp:listen(0, [binary, {packet, line}, {active, false}, {reuseaddr, true}]), {ok, Port} = inet:port(Listen), Table = ets:new(sockets, [named_table, public, set]), Acceptor = spawn_link(fun() -> accept_loop(Listen, Table) end), {ok, A} = join(Port), {ok, B} = join(Port), io:format("joined: ~p~n", [{is_port(A), is_port(B)}]), ok = gen_tcp:send(A, "hello\n"), io:format("broadcast: ~p ~p~n", [recv_line(A), recv_line(B)]), ok = gen_tcp:close(A), _ = wait_for_size(Table, 1, 100), io:format("live sockets: ~p~n", [ets:info(Table, size)]), ok = gen_tcp:close(B), unlink(Acceptor), exit(Acceptor, shutdown), ok = gen_tcp:close(Listen). join(Port) -> {ok, Socket} = gen_tcp:connect({127, 0, 0, 1}, Port, [binary, {packet, line}, {active, false}]), {ok, _Ack} = gen_tcp:recv(Socket, 0, 1000), {ok, Socket}. recv_line(Socket) -> {ok, Line} = gen_tcp:recv(Socket, 0, 1000), Line. wait_for_size(_Table, _Size, 0) -> ok; wait_for_size(Table, Size, Tries) -> case ets:info(Table, size) of Size -> ok; _Other -> timer:sleep(10), wait_for_size(Table, Size, Tries - 1) end. accept_loop(Listen, Table) -> case gen_tcp:accept(Listen) of {ok, Socket} -> true = ets:insert(Table, {Socket}), ok = gen_tcp:send(Socket, "joined\n"), spawn(fun() -> handler(Socket, Table) end), accept_loop(Listen, Table); {error, closed} -> ok end. handler(Socket, Table) -> case gen_tcp:recv(Socket, 0, 60000) of {ok, Line} -> broadcast(Line, Table), handler(Socket, Table); {error, closed} -> true = ets:delete(Table, Socket), ok end. broadcast(Line, Table) -> [gen_tcp:send(Socket, Line) || {Socket} <- ets:tab2list(Table)], ok.

erlc chat.erl

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

joined: {true,true} broadcast: <<"hello\n">> <<"hello\n">> live sockets: 1

The acceptor never reads a client, so a slow or stuck client cannot hold it back: accept takes the next connection at once and a fresh process does the reading. join/1 waits for the welcome line before it returns, which proves the socket is already in the table and a broadcast cannot miss it.

The table of sockets

The table is what makes a broadcast possible: every handler walks it and sends the same line to every socket, the sender included. A production server deletes the rows whose send failed, caps the number of clients and gives each send a timeout, because gen_tcp:send blocks when a peer stops reading and its buffer fills. The ETS lesson covers the table itself, and the in depth TCP lesson shows the controlling_process call that hands a socket from the acceptor to its handler.

A client that leaves

Closing from the client side makes the handler recv answer {error, closed}, and that clause removes the socket from the table and ends the process. In the program above the table falls from two rows to one after the first client closes, which the third line of the output shows. The listening socket is untouched, so the next client is accepted on the same port.

To put the server into an OTP application, wrap the acceptor in a gen_server, put the listen socket in the server state, and let a supervisor restart the whole thing if the acceptor ever dies. The clients already run as independent processes, which is what lets the tree survive one bad connection.

Questions

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

  1. Why does the accept loop never read from a client?

    Answer

    So a slow client cannot hold back the next accept

    The accept loop only accepts; a fresh handler process does the reading.

  2. Why does start/0 listen on port 0?

    Answer

    So the kernel picks a free port

    An ephemeral port avoids clashes, and inet:port/1 reports the number.

  3. Why does the ETS table hold the client sockets?

    Answer

    So the broadcast can send to every client

    Every handler can walk the shared table and reach all live sockets.

  4. What does join/1 wait for before it returns?

    Answer

    The welcome line from the server

    The ack proves that the socket is already in the table, so a broadcast cannot miss it.

  5. What does {packet, line} do to a socket?

    Answer

    Delivers whole lines

    The driver splits the stream at the newline, so a recv never returns half a message.

  6. What does gen_tcp:recv/3 answer when the client disconnects?

    Answer

    {error, closed}

    The closed socket is the normal end of a client, and the handler uses it to clean up.

  7. What does this module print? -module(q1). -export([main/0]). main() -> {ok, Listen} = gen_tcp:listen(0, [{active, false}]), {ok, Port} = inet:port(Listen), io:format("~p~n", [is_integer(Port)]), ok = gen_tcp:close(Listen).

    Answer

    true

    Port 0 asks the kernel for a free port, and inet:port/1 answers its number.

  8. What does this module print? -module(q2). -export([main/0]). main() -> io:format("~p~n", [gen_tcp:connect({127, 0, 0, 1}, 1, [], 200)]).

    Answer

    {error, econnrefused}

    No process listens on port 1, and the operating system refuses the connection.

  9. What does this module print? -module(q3). -export([main/0]). main() -> io:format("~p~n", [inet:ntoa({127, 0, 0, 1})]).

    Answer

    "127.0.0.1"

    inet:ntoa/1 turns an address tuple into its text form.

  10. What does this module print? -module(q4). -export([main/0]). main() -> {ok, Listen} = gen_tcp:listen(0, [{active, false}]), {ok, Port} = inet:port(Listen), Self = self(), spawn(fun() -> {ok, Client} = gen_tcp:connect({127, 0, 0, 1}, Port, []), ok = gen_tcp:close(Client), Self ! closed end), {ok, Socket} = gen_tcp:accept(Listen), receive closed -> ok end, io:format("~p~n", [gen_tcp:recv(Socket, 0, 1000)]).

    Answer

    {error, closed}

    The client closed its end, so the server side of the socket reports it as 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. The sockets use the loopback address, so no network leaves the machine.

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