Skip to content

Commit ba7677a

Browse files
committed
update tcp_connection example
1 parent 00c6958 commit ba7677a

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

.formatter.exs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
# Used by "mix format"
22
[
3-
inputs: ["{mix,.formatter}.exs", "{config,lib,test,integration_test}/**/*.{ex,exs}"]
3+
inputs: ["{mix,.formatter}.exs", "{config,lib,test,examples,integration_test}/**/*.{ex,exs}"]
44
]

examples/tcp_connection/lib/tcp_connection.ex

+9
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,8 @@ defmodule TCPConnection do
6464

6565
case :gen_tcp.connect(host, port, socket_opts, timeout) do
6666
{:ok, sock} ->
67+
# Monitor the socket so we can react to it being closed. See handle_info/2.
68+
_ref = :inet.monitor(sock)
6769
{:ok, {sock, <<>>}}
6870

6971
{:error, reason} ->
@@ -143,6 +145,13 @@ defmodule TCPConnection do
143145
end
144146
end
145147

148+
# The handle_info callback is optional and can be removed if not needed.
149+
# Here it is used to react to `:inet.monitor/1` messages which arrive
150+
# when socket gets closed while the connection is idle.
151+
def handle_info({:DOWN, _ref, _type, sock, _info}, {sock, _buffer} = s) do
152+
{:disconnect, TCPConnection.Error.exception({:idle, :closed}), s}
153+
end
154+
146155
@impl true
147156
def handle_close(_, _, s) do
148157
{:ok, nil, s}

0 commit comments

Comments
 (0)