:httpc and :gen_tcp
Networking in Elixir is the networking of Erlang/OTP: :gen_tcp opens a socket, and :httpc speaks HTTP on top of it. Both are in the standard library, so a program that needs one request does not need a dependency. This page starts a server and a client in one program, on the loopback address, which is the network this environment allows.
gen_tcp: a connection
:gen_tcp.listen/2 opens a listening socket; port 0 asks the system for a free port, and :inet.port/1 answers which one. A process accepts one connection, reads and answers, and the client sends a line and reads the reply:
tcp.exs
{:ok, listen} = :gen_tcp.listen(0, [:binary, packet: :raw, active: false, reuseaddr: true]) {:ok, port} = :inet.port(listen) spawn(fn -> {:ok, socket} = :gen_tcp.accept(listen) {:ok, request} = :gen_tcp.recv(socket, 0) :gen_tcp.send(socket, "echo: " <> request) :gen_tcp.close(socket) end) {:ok, client} = :gen_tcp.connect(~c"127.0.0.1", port, [:binary, active: false]) :gen_tcp.send(client, "hello") {:ok, reply} = :gen_tcp.recv(client, 0) IO.puts(reply) :gen_tcp.close(client) :gen_tcp.close(listen) Process.sleep(20)
elixir tcp.exs
echo: hello
The server process blocks in accept/1 until the client connects, then in recv/2 until the bytes arrive. The port is not printed because the system chooses it; the program passes it from the listener to the client in one variable. The short sleep at the end gives the server time to finish before the script ends.
httpc: an HTTP client
:httpc belongs to the inets application, which must be started first. The request takes the method, a tuple of the URL and the headers, the HTTP options and the options of the call; body_format: :binary makes the body a binary rather than a charlist:
http.exs
{:ok, listen} = :gen_tcp.listen(0, [:binary, packet: :raw, active: false, reuseaddr: true]) {:ok, port} = :inet.port(listen) spawn(fn -> {:ok, socket} = :gen_tcp.accept(listen) {:ok, _request} = :gen_tcp.recv(socket, 0) :gen_tcp.send(socket, "HTTP/1.1 200 OK\r\ncontent-length: 5\r\n\r\nhello") :gen_tcp.close(socket) end) {:ok, _} = Application.ensure_all_started(:inets) url = ~c"http://127.0.0.1:#{port}/" {:ok, {{_, 200, _}, _headers, body}} = :httpc.request(:get, {url, []}, [], body_format: :binary) IO.puts(body) :gen_tcp.close(listen)
elixir http.exs
hello
The server writes the smallest valid HTTP response: a status line, a content length and the body. The client matches the status and the body, so a server that answered 404 would fail the match rather than print a page of HTML. A real client adds a timeout and the headers it needs; the shape of the call is the same.
The URL and the port
The URL of :httpc is a charlist, which is why the example writes ~c"http://..." and not a binary. The port is a number the program asks the system for, so two runs of the page do not collide. A program that calls a real server writes the host and the port it was given, and the environment of the machine decides them; the configuration lesson shows where that value belongs.
The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container. They use the loopback interface only; the environment has no external network.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which OTP module opens a TCP connection?
Answer
:gen_tcp
gen_tcp is the Erlang TCP module; httpc builds HTTP on top of the socket layer.
-
What does port 0 mean in
:gen_tcp.listen/2?Answer
Ask the system for a free port
The system assigns a free port, and :inet.port/1 reports which one.
-
Which application must be started before
:httpc.request/4?Answer
:inets
httpc is part of inets, so the application has to run first.
-
What type is the URL of
:httpc?Answer
A charlist
The Erlang API takes a charlist URL, written ~c"..." in Elixir.
-
What does this program print?
{:ok, listen} = :gen_tcp.listen(0, [:binary, active: false]) {:ok, port} = :inet.port(listen) IO.puts(is_integer(port)) :gen_tcp.close(listen)Answer
true
inet.port/1 answers the port as an integer, so the check is true.
-
What does this program print?
{:ok, _} = Application.ensure_all_started(:inets) IO.puts(:inets.module_info(:module))Answer
:inets
module_info/1 answers the module name as an atom.
-
What does
:gen_tcp.recv(socket, 0)do?Answer
Waits for the next bytes available on the socket
Length 0 means "all available data" in passive mode.
-
Which status line does a server that answers with 200 write?
Answer
HTTP/1.1 200 OK
The server answers with a 200 status and a body of five bytes.
-
Why does the page not print the port?
Answer
The system chooses it and it changes between runs
The port of a listener on 0 is assigned at run time, so the page shows behaviour instead.
-
What does the server process do in the TCP example?
Answer
Accepts one connection, reads the request and sends the reply
The spawned process is the one-connection server.
Article author: Arthur Isaev