Sockets
TCP in one process
gen_tcp speaks TCP. listen opens a server socket, connect opens a client socket, and accept takes one connection off the queue. Port 0 asks the kernel for a free port, and inet:port reads the number back. Save this module as tcp_echo.erl; the server and the client live in one process here, because the kernel completes the handshake as soon as connect returns.
-module(tcp_echo).
-export([round_trip/1, closed/0]).
round_trip(Data) ->
{ok, Client, Server, _Listen} = connect(),
ok = gen_tcp:send(Client, [Data, $\n]),
{ok, Line} = gen_tcp:recv(Server, 0, 1000),
ok = gen_tcp:send(Server, Line),
Echo = gen_tcp:recv(Client, 0, 1000),
close(Client, Server),
Echo.
closed() ->
{ok, Client, Server, Listen} = connect(),
ok = gen_tcp:close(Server),
Result = gen_tcp:recv(Client, 0, 1000),
ok = gen_tcp:close(Client),
ok = gen_tcp:close(Listen),
Result.
connect() ->
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, Client, Server, Listen}.
close(Client, Server) ->
ok = gen_tcp:close(Client),
ok = gen_tcp:close(Server).
The options matter more than the calls. binary makes recv answer a binary instead of a string, {active, false} keeps the socket passive so recv can read it, {packet, line} turns one line into one message, and {reuseaddr, true} lets the port be bound again right after a restart.
Packet modes
A TCP stream is a stream of bytes: nothing marks where one message ends. 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 you whatever arrived.
erlc tcp_echo.erl
erl
1> tcp_echo:round_trip(<<"hello">>).
{ok,<<"hello\n">>}
2> tcp_echo:round_trip(<<"second line">>).
{ok,<<"second line\n">>}
Both sides must agree on the packet mode. Set line on the listener and raw on the client and the client sees the newline as plain data, which is fine, but set 4 on one side only and that side waits for a length prefix the other never sends.
UDP datagrams
gen_udp sends datagrams: no connection, no handshake, one send is one recv, and a lost datagram is lost. The address travels with the call instead of living in a socket. Save this module as udp_echo.erl.
-module(udp_echo).
-export([round_trip/1]).
round_trip(Data) ->
Opts = [binary, {active, false}],
{ok, Sender} = gen_udp:open(0, Opts),
{ok, Receiver} = gen_udp:open(0, Opts),
{ok, Port} = inet:port(Receiver),
ok = gen_udp:send(Sender, {127, 0, 0, 1}, Port, Data),
{ok, {_Address, _From, Packet}} = gen_udp:recv(Receiver, 0, 1000),
ok = gen_udp:close(Sender),
ok = gen_udp:close(Receiver),
Packet.
erlc udp_echo.erl
erl
1> udp_echo:round_trip(<<"ping">>).
<<"ping">>
UDP is the right choice for a metric that may be dropped, or for a broadcast on a local network. It is the wrong choice for anything a user waits for, because nothing retransmits it and nothing tells you it is gone.
Closing a connection
close sends the FIN and frees the socket, and the other side sees the end of the stream. recv on a socket whose peer closed answers {error, closed}, which is the normal way a handler learns that the client is done.
erl
1> tcp_echo:closed().
{error,closed}
The listening socket stays open through all of this, so the next client is accepted on the same port. Only the accepted socket is closed here.
Next: HTTP clients
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which call opens a listening TCP socket?
Answer
gen_tcp:listen/2listenreturns the server socket thataccepttakes connections from. -
What does port 0 ask the kernel for?
Answer
Any free port
The kernel picks a free ephemeral port, and
inet:port/1reads the number back. -
What does
{active, false}give you?Answer
A passive socket that
recvcan readWith active true the messages arrive in the mailbox and
recvrefuses to read the socket. -
What does
{packet, line}do?Answer
Splits the stream on newlines, one line per message
The framing is done for you, so each
recvanswers one line including its newline. -
What does
{packet, 4}mean?Answer
A four byte big endian length prefix
The receiver reads the prefix first and then exactly that many bytes.
-
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.
-
What is the difference between
gen_tcpandgen_udp?Answer
TCP is a connected stream, UDP sends datagrams
TCP keeps a connection and retransmits, UDP sends independent datagrams with no delivery promise.
-
How many recv calls does one UDP datagram need?
Answer
One
Each datagram arrives whole, so a single recv gives back the whole payload.
-
What does
gen_tcp:recv/3answer when the peer has closed the connection?Answer
{error, closed}The closed peer is reported as a closed socket, which is how a handler sees the end of a client.
-
Which socket does
tcp_echo:closed/0close before it reads?Answer
The accepted server socket
Closing the accepted side ends the stream, so the client read reports closed while the listener stays open.
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