WebSocket and HTTP fails silently

The behavior you’re observing might seem like a runtime issue, but it’s actually how Julia handles OS signals.

Additionally, some of the other problems with these minimal examples are due to incorrect API usage (specifically with the HTTP package):

  • Use send() instead of write() to send data to a WebSocket.
  • Use isopen(ws.io) instead of isopen(ws) to properly check connection status.

If you’re looking to handle Ctrl-C interruptions and signal handling correctly, here’s a minimal example using Visor:

using Visor
using HTTP.WebSockets

mutable struct WS
    ws::Union{Nothing,WebSockets.WebSocket}
    inbox::Channel
    WS(inbox) = new(nothing, inbox)
end

function receive(sock::WS)
    while isopen(sock.ws.io)
        msg = WebSockets.receive(sock.ws)
        put!(sock.inbox, msg)
    end
end

function ws_process(pd)
    sock = WS(pd.inbox)
    count = 1

    @async WebSockets.open("wss://echo.websocket.org") do ws
        sock.ws = ws
        receive(sock)
    end

    for msg in pd.inbox
        if isshutdown(msg)
            @info "Shutting down"
            close(sock.ws)
            break
        end
        @info "Received message: $msg"
        sleep(1)
        WebSockets.send(sock.ws, "hello $count")
        count += 1
    end
end

supervise(process(ws_process))

Disclaimer: I’m the author of Visor, and I created this package to overcome the same issues you’re facing

3 Likes