Responding over a TCP socket using :gen_tcp
Now that we know how to use :gen_tcp
to initiate a TCP/IP connection, the next step is to respond using that connection. In order to respond to a request, we will be using the :
gen_tcp.send/2
function.
The :gen_tcp.send/2
function allows us to send I/O data (generally string) on a connection socket. It doesn’t support send timeout, so it only takes a connection socket and data that needs to be sent. We can use the connection socket returned by the :gen_tcp.accept/1
call in the previous section to send an HTTP response.
In order to send data over a connection socket, let’s restructure our ExperimentServer
module:
experiment_server.exs
defmodule ExperimentServer do require Logger def start(port) do listener_options = [ active: false, packet: :http_bin, reuseaddr: true ] ...