diff --git a/.formatter.exs b/.formatter.exs index be68757e..ab786a03 100644 --- a/.formatter.exs +++ b/.formatter.exs @@ -1,4 +1,4 @@ # Used by "mix format" [ - inputs: ["{mix,.formatter}.exs", "{config,lib,test,integration_test}/**/*.{ex,exs}"] + inputs: ["{mix,.formatter}.exs", "{config,lib,test,examples,integration_test}/**/*.{ex,exs}"] ] diff --git a/examples/tcp_connection/lib/tcp_connection.ex b/examples/tcp_connection/lib/tcp_connection.ex index efb68352..29a17048 100644 --- a/examples/tcp_connection/lib/tcp_connection.ex +++ b/examples/tcp_connection/lib/tcp_connection.ex @@ -64,6 +64,8 @@ defmodule TCPConnection do case :gen_tcp.connect(host, port, socket_opts, timeout) do {:ok, sock} -> + # Monitor the socket so we can react to it being closed. See handle_info/2. + _ref = :inet.monitor(sock) {:ok, {sock, <<>>}} {:error, reason} -> @@ -143,6 +145,13 @@ defmodule TCPConnection do end end + # The handle_info callback is optional and can be removed if not needed. + # Here it is used to react to `:inet.monitor/1` messages which arrive + # when socket gets closed while the connection is idle. + def handle_info({:DOWN, _ref, _type, sock, _info}, {sock, _buffer} = s) do + {:disconnect, TCPConnection.Error.exception({:idle, :closed}), s} + end + @impl true def handle_close(_, _, s) do {:ok, nil, s}