Inducing a Task to finish

I’m afraid there a lot of moving parts in this question. I’ve created a Task that reads from a Channel and writes to a WebSocket. I’d like to be able to wait() for the Task to finish, and I’d like the Task to finish when the WebSocket has been closed by the client at its other end. Here’s what the function looks like:

function listener(port::Int64, channel::Channel)
    HTTP.listen(Sockets.localhost, port) do http::HTTP.Stream
        if HTTP.WebSockets.is_upgrade(http.message)
            HTTP.WebSockets.upgrade(http, binary=true) do ws
                try
                    while !eof(ws)
                        _ = readavailable(ws)
                        bytes = take!(channel)
                        write(ws, bytes)
                    end
                catch err
                    if isa(err, InvalidStateException)
                        @info "Channel for $port is closed, exiting"
                    end
                end
            end
        end
    end
end

One thing I’ve tried that is partly successful (but pretty ugly), is to call throwto(task, InterruptException()). Among the many things I don’t like about that approach is that listener() isn’t directly responding to its websocket being closed.

1 Like