Stream: helpdesk (published)

Topic: Safe way to check if socket is open


view this post on Zulip DrChainsaw (Jul 05 2024 at 09:38):

Is there a safe way to check if a (UDP)Socket is open without reaching into internals?

using Sockets

julia> isopen(UDPSocket())
ERROR: ArgumentError: UDPSocket(init) is not initialized
Stacktrace:
 [1] isopen(x::UDPSocket)
   @ Base .\stream.jl:381
 [2] top-level scope
   @ REPL[11]:1

I know that the status is accessible as a property, but the interpretation of it seem to be internals.

My current workaround is to wrap the socket in a struct which can only be created in such a way that the socket is bound upon creation and make my functions only accept this struct as input.

Is this the idiomatic way?

view this post on Zulip James Wrigley (Jul 05 2024 at 10:12):

Not sure if there's an idiomatic way, but another option would be to define and use e.g.:

function isopen_nothrow(sock)
    try
        isopen(sock)
    catch ex
        if isa(ex, ArgumentError)
            return false
        else
            rethrow()
        end
    end
end

view this post on Zulip DrChainsaw (Jul 05 2024 at 10:30):

How is the performance of this?

Would it be ok to have in a readloop like this without it being a source of dropped packets:

while isopen_nothrow(sock)
    processpacket(recv(sock))
end

Although I guess the while thing there is pretty pointless since it is unlikely that you will hit it rather than getting an EOFError from recv.

view this post on Zulip James Wrigley (Jul 05 2024 at 10:36):

There'll probably be some overhead, but you could avoid it by calling isopen_nothrow() once before the loop and using while isopen(sock). That should work because the status won't be reset to any init/uninit flag after the socket has been opened.


Last updated: Dec 28 2024 at 04:38 UTC