Listening over a TCP socket using :gen_tcp
Cowboy uses Ranch to create and manage a TCP connection, but in our web server, we will be using the :gen_tcp
module. This module allows two entities to communicate using TCP/IP sockets and is shipped as a part of Erlang’s Open Telecom Platform (OTP).
We need to first listen on a TCP/IP port and accept requests on a TCP socket. Once the request is processed and a response is sent, we also need to close the connection and socket.
Here are the functions we will be using:
:gen_tcp.listen/2
: Accepts a listening port and server options. Creates a listening socket that listens on a given TCP/IP port.:gen_tcp.accept/2
: Accepts a listening socket returned by:gen_tcp.listen/2
and a timeout, which defaults to infinity. This function creates another socket that represents a connection between the server and the client. This socket is used to send a response to the client from the server. Since web servers are long-running processes...