Skip to content

How to handle connection close for websocket #1060

@AbhimanyuAryan

Description

@AbhimanyuAryan

Currently when I kill a terminal session for a client using CTRL+C I catch the error as EOFError however I would like to catch something like WebSocketClosedError. How can I properly handle it when a connection is closed or the client is disconnected?

server.jl

using HTTP
using JSON

WebSockets.listen("127.0.0.1", UInt16(8080)) do ws
    try
        for msg in ws
            data = JSON.parse(String(msg))
            clientName = data["clientName"]
            message = data["message"]
            println("Received data from ", clientName, ": ", message)
        end
    catch e
        if isa(e, EOFError)
            println("A client has disconnected.")
        else
            rethrow(e)
        end
    end
end

client.jl

using HTTP
using JSON

function start_client(ws)
    println("Enter your name: ")
    clientName = readline()
    println("You can start typing your messages now. Press Ctrl+C to quit.")
    while true
        write(stdout, "> ")
        message = readline()
        
        data = Dict("clientName" => clientName, "message" => message)
        json_data = JSON.json(data)
        
        HTTP.WebSockets.send(ws, json_data)
    end
end

HTTP.WebSockets.open(start_client, "ws://127.0.0.1:8080")

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions