Timeout for connect (Socket)

I’ll give my usual warning: if you are attempting to deal with time-outs, you are probably setting up your application logic wrong, which may lead to headaches, or worse, could accidentally create packet storms that DoS your network and host (plus, it doesn’t actually block infinitely, since your operating system already came with a connect timeout that you can probably configure. I think a typical default is to continue retrying, with the necessary exponential backoff, for about 2 minutes).

But it is quite simple: the wait-able objects in Julia are expected to support the close operation and can be used as cancellation tokens:

julia> t = TCPSocket();

julia> Timer(_ -> close(t), 5);

julia> connect(t, "1.2.3.4", 8000)
ERROR: IOError: connect: operation canceled (ECANCELED)
Stacktrace:
 [1] wait_connected(x::TCPSocket)
   @ Sockets /data/vtjnash/julia/usr/share/julia/stdlib/v1.7/Sockets/src/Sockets.jl:532
 [2] connect(::TCPSocket, ::String, ::Int64)
   @ Sockets /data/vtjnash/julia/usr/share/julia/stdlib/v1.7/Sockets/src/Sockets.jl:567
 [3] top-level scope
   @ REPL[13]:1

julia> # TODO: using the same cancellation concept as before, we need close(timer) here too
4 Likes