Sockets

A socket is a port number and a conversation. Erlang reaches the TCP stack through gen_tcp, which lives in the kernel application: a server opens a listening socket, takes one connection at a time off its queue, and then reads and writes bytes on it. This lesson keeps the server and the client in one process, which is enough to see every call and every option; the TCP server in depth lesson gives each connection a process of its own.

One connection

gen_tcp:listen/2 opens the server socket; port 0 asks the kernel for a free port, and inet:port/1 reads the number back, which is how a test server finds a port without a constant. gen_tcp:connect/3 opens the client, and gen_tcp:accept/2 takes the connection off the queue. The options decide the type of what a read answers and who reads it:

tcp_echo.erl

-module(tcp_echo). -export([main/0]). main() -> Opts = [binary, {packet, line}, {active, false}, {reuseaddr, true}], {ok, Listen} = gen_tcp:listen(0, Opts), {ok, Port} = inet:port(Listen), {ok, Client} = gen_tcp:connect({127, 0, 0, 1}, Port, Opts), {ok, Server} = gen_tcp:accept(Listen, 1000), ok = gen_tcp:send(Client, <<"hello\n">>), {ok, Line} = gen_tcp:recv(Server, 0, 1000), ok = gen_tcp:send(Server, Line), {ok, Echo} = gen_tcp:recv(Client, 0, 1000), io:format("server read: ~p~n", [Line]), io:format("client read: ~p~n", [Echo]), ok = gen_tcp:close(Client), ok = gen_tcp:close(Server), ok = gen_tcp:close(Listen).

erlc tcp_echo.erl

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

server read: <<"hello\n">> client read: <<"hello\n">>

The options matter more than the calls. binary makes a read answer a binary instead of a string, which is what the rest of this chapter works with. {active, false} keeps the socket passive, so only recv reads it; an active socket sends its data to the owner as messages instead. {packet, line} frames the stream by newline, and {reuseaddr, true} lets the port be bound again right after a restart instead of waiting out the operating system.

Packet modes

A TCP stream is a stream of bytes: nothing in it marks where one message ends and the next begins. The packet option does the framing for you. line splits on the newline, 1 reads one byte at a time, 2 and 4 read a big endian length prefix followed by that many bytes, and raw hands over whatever arrived. Each side frames its own socket, so the two must agree: this program reads the first message with the wrong mode on purpose, and then sets the right one:

framing.erl

-module(framing). -export([main/0]). main() -> {ok, Listen} = gen_tcp:listen(0, [binary, {active, false}]), {ok, Port} = inet:port(Listen), {ok, Client} = gen_tcp:connect({127, 0, 0, 1}, Port, [binary, {active, false}]), {ok, Server} = gen_tcp:accept(Listen, 1000), ok = inet:setopts(Server, [{packet, 4}]), ok = gen_tcp:send(Server, <<"hi">>), {ok, Raw} = gen_tcp:recv(Client, 6, 1000), ok = inet:setopts(Client, [{packet, 4}]), ok = gen_tcp:send(Server, <<"again">>), {ok, Framed} = gen_tcp:recv(Client, 0, 1000), io:format("raw bytes: ~w~n", [Raw]), io:format("framed: ~p~n", [Framed]), ok = gen_tcp:close(Server), ok = gen_tcp:close(Client), ok = gen_tcp:close(Listen).

erlc framing.erl

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

raw bytes: <<0,0,0,2,104,105>> framed: <<"again">>

The raw read shows the whole frame: four bytes of length, then the two bytes of the message. With the mode set on both sides, recv answers only the payload. A server that sets 4 on its side and a client that keeps raw does not fail: it reads a length prefix as data, which is the worse failure, because the first message looks plausible and the second one is off by four bytes.

Timeouts and the end

Every blocking socket call takes a timeout, and the timeout is the difference between a server that waits and a server that hangs. gen_tcp:accept/2 with nobody connecting answers {error, timeout}; gen_tcp:recv/3 on an idle socket does the same; and a recv whose peer has closed answers {error, closed}, which is the normal end of a connection and not a failure:

timeouts.erl

-module(timeouts). -export([main/0]). main() -> {ok, Listen} = gen_tcp:listen(0, [binary, {active, false}]), {ok, Port} = inet:port(Listen), io:format("accept with nobody there: ~p~n", [gen_tcp:accept(Listen, 100)]), {ok, Client} = gen_tcp:connect({127, 0, 0, 1}, Port, [binary, {active, false}]), {ok, Server} = gen_tcp:accept(Listen, 1000), io:format("recv with nothing sent: ~p~n", [gen_tcp:recv(Client, 0, 100)]), ok = gen_tcp:close(Server), io:format("recv after the peer closed: ~p~n", [gen_tcp:recv(Client, 0, 100)]), ok = gen_tcp:close(Client), ok = gen_tcp:close(Listen).

erlc timeouts.erl

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

accept with nobody there: {error,timeout} recv with nothing sent: {error,timeout} recv after the peer closed: {error,closed}

The three answers need three different reactions. A timeout is worth a retry or a log line, a closed peer ends the handler, and an accept timeout is what lets an acceptor check its mailbox and stop when the tree shuts down. A read without a timeout in a server is the mistake this lesson warns about: a client that connects and never sends keeps that handler busy for as long as it likes, and the next lesson gives every connection its own process so that one quiet client cannot hold up the rest.

UDP

gen_udp is the same module family without a connection: one send is one datagram, one recv is one datagram, and nothing retransmits a loss. The UDP and inet lesson covers it, together with the address functions and the options every socket shares. An HTTP client over TCP is the next lesson but one.

Questions

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

  1. Which call opens a listening TCP socket?

    Answer

    gen_tcp:listen/2

    listen returns the server socket that accept takes connections from.

  2. What does port 0 ask the kernel for?

    Answer

    Any free port

    The kernel picks a free ephemeral port, and inet:port/1 reads the number back.

  3. What does {active, false} give you?

    Answer

    A passive socket that recv can read

    With active true the messages arrive in the mailbox, and recv is not the reader.

  4. What does {packet, 4} mean?

    Answer

    A four byte big endian length prefix

    The sender writes the length first and the receiver reads exactly that many bytes.

  5. Why must both sides agree on the packet mode?

    Answer

    Each side frames the bytes itself

    Framing is local to each socket, so mismatched modes read the same bytes into different messages.

  6. What does gen_tcp:recv/3 answer when the peer has closed the connection?

    Answer

    {error, closed}

    A closed peer is reported as a closed socket, which is how a handler sees the end of a client.

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

    Answer

    {ok,<<"ping">>}

    A raw socket with a length of four gives exactly the four bytes that were sent.

  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 = gen_tcp:send(Client, <<"alpha\nbeta\n">>), R = gen_tcp:recv(Server, 0, 1000), ok = gen_tcp:close(Client), ok = gen_tcp:close(Server), ok = gen_tcp:close(Listen), io:format("~p~n", [R]).

    Answer

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

    In line mode each read answers one line, newline included, however many lines were sent.

  9. What does this module print? -module(q3). -export([main/0]). main() -> {ok, Listen} = gen_tcp:listen(0, [binary, {active, false}]), {ok, _Port} = inet:port(Listen), R = gen_tcp:accept(Listen, 50), ok = gen_tcp:close(Listen), io:format("~p~n", [R]).

    Answer

    {error,timeout}

    Nobody connects within fifty milliseconds, so the accept reports its timeout.

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

    Answer

    {error,closed}

    The peer closed the connection, so the read answers closed rather than waiting for the timeout.

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