Capstone: TCP server
Start the server
The second capstone is a chat server: many clients, one message reaching all of them. The shape is the classic Erlang one, and it is shorter than the same program in most languages: a listening socket, one acceptor process, one handler process per client, and an ETS table of the live sockets for the broadcast of lesson 42. Save this module as chat.erl.
-module(chat).
-export([start/0, stop/0, join/1, say/2, received/1, close/1]).
-define(TABLE, chat_sockets).
start() ->
{ok, Listen} = gen_tcp:listen(0, [binary, {packet, line}, {active, false}, {reuseaddr, true}]),
{ok, Port} = inet:port(Listen),
ets:new(?TABLE, [named_table, public]),
Pid = spawn(fun() -> accept(Listen) end),
register(chat_server, Pid),
{ok, Port}.
stop() ->
case whereis(chat_server) of
undefined ->
ok;
Pid ->
exit(Pid, shutdown),
ok
end.
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}.
say(Socket, Text) ->
gen_tcp:send(Socket, [Text, "\n"]).
received(Socket) ->
gen_tcp:recv(Socket, 0, 1000).
close(Socket) ->
gen_tcp:close(Socket).
accept(Listen) ->
case gen_tcp:accept(Listen) of
{ok, Socket} ->
ets:insert(?TABLE, {Socket}),
ok = gen_tcp:send(Socket, "joined\n"),
spawn(fun() -> handler(Socket) end),
accept(Listen);
{error, closed} ->
ok
end.
handler(Socket) ->
case gen_tcp:recv(Socket, 0, 60000) of
{ok, Line} ->
broadcast(Line),
handler(Socket);
{error, closed} ->
ets:delete(?TABLE, Socket)
end.
broadcast(Line) ->
[gen_tcp:send(Socket, Line) || {Socket} <- ets:tab2list(?TABLE)].
The accept loop 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. The table holds the live sockets, and the named process makes stop/0 possible from anywhere. A real server would also cap the number of clients and drop the sockets that broadcast finds closed.
Join and send
join/1 is the client side: connect, then wait for the welcome line that accept sends. Waiting for the ack is what makes the table consistent, because by the time the client returns, its socket is already in the table. The session starts the server on a free port, joins, says one line and reads the echo.
erlc chat.erl
erl
1> {ok, Port} = chat:start(), is_integer(Port).
true
2> {ok, Socket} = chat:join(Port), is_port(Socket).
true
3> chat:say(Socket, "hello").
ok
4> chat:received(Socket).
{ok,<<"hello\n">>}
Port 0 lets the kernel pick a free port, and start/0 answers the number, so two servers can run side by side and a test never clashes with a port in use. That is also why the transcript has no port number in it: the number changes on every run.
Broadcast to all
Two clients, one message, and both receive it: that is the whole point of the server. The broadcast walks the table and sends the same line to every socket, including the one that sent it.
erl
1> {ok, Port} = chat:start(), is_integer(Port).
true
2> {ok, A} = chat:join(Port), {ok, B} = chat:join(Port), {is_port(A), is_port(B)}.
{true,true}
3> chat:say(A, "hello").
ok
4> {chat:received(A), chat:received(B)}.
{{ok,<<"hello\n">>},{ok,<<"hello\n">>}}
Because each handler process blocks in its own recv, the clients are independent: a client that stops reading only fills its own socket buffer. When that buffer is full, gen_tcp:send blocks until the peer reads again or the send timeout expires, and the broadcast stalls for everybody, which is why a production server sets a send timeout on the socket or lets each handler do its own sending. It also uses {active, once} and a receive loop instead of a blocking recv, and closes the dead sockets during the broadcast.
Close the connection
Closing the socket from the client side makes the handler recv answer {error, closed}, and that clause removes the socket from the table and ends the process. The listening socket is untouched, so the next client is accepted on the same port.
erl
1> {ok, Port} = chat:start(), is_integer(Port).
true
2> {ok, Socket} = chat:join(Port), is_port(Socket).
true
3> chat:close(Socket).
ok
4> chat:received(Socket).
{error,closed}
5> chat:stop().
ok
To put this server into a real OTP application, wrap the acceptor in a gen_server with a supervisor of lesson 35 around it, put the listen socket in the server state, and let the supervisor restart the whole thing if the acceptor ever dies. The clients themselves already run as independent processes, which is what makes the tree survive one bad connection.
Next: Performance
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
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.
-
Why does
start/0listen on port 0?Answer
So the kernel picks a free port
An ephemeral port avoids clashes, and
inet:port/1reports the number. -
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.
-
What does
join/1wait 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.
-
What happens to a client socket when its handler process ends?
Answer
It is closed with the process
The socket belongs to the process, so the handler ending closes it.
-
What does
gen_tcp:recv/3answer 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.
-
Why does one handler per client keep the server responsive?
Answer
The scheduler runs the handlers independently
A blocked handler waits alone, while the other handlers and the acceptor keep running.
-
Which mode would a busy production server prefer over blocking
recv?Answer
{active, once}with a receive loopActive once hands one message at a time to the process mailbox, so it can also handle other messages.
-
How would this server go into an OTP application?
Answer
Wrap the acceptor in a gen_server under a supervisor
The supervisor restarts the acceptor if it dies, which is the OTP shape of the same program.
-
What does
broadcast/1do with a socket that has gone away?Answer
Leaves the failed send and the dead row for the handler to clean
The failed send is ignored here; a production version would delete the dead socket during the walk.
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.
Article author: Arthur Isaev