How to correctly detect closed TCP connection

One possible solution I have figured out is to use Channel to asynchronously wait on the eof.

function is_socket_eof(channel::Channel, sock)
    put!(channel, eof(sock))
end

function is_socket_closed(sock, eof_monitor::Channel)
    return !isopen(sock) || (isready(eof_monitor) && take!(eof_monitor))
end

function write_data(sock)
    eof_monitor = Channel((ch) -> is_socket_eof(ch, sock))
    while !is_socket_closed(sock, eof_monitor)
        write(sock,"hello\n")
        sleep(1)
    end
    println("socket closed")
end

This seems to correctly detect if the socket was closed remotely.

I am unsure why I do have to put the !isopen(sock) to the is_socket_closed function. Without it, I have found out that the condition in the while !is_socket_closed(...) would result to true and yet ‘isopen(sock)’ would be false resulting in an error when writing to the socket. Maybe something connected with the asynchronicity which I don’t fully understand yet.

If someone would have an idea for better solution, it would be appreciated.

3 Likes