Skip to content

WebSocket - Opening a connection to a non-existent server fire a error but keeps CONNECTING state indefinitely #3506

@alexojegu

Description

@alexojegu

Bug Description

WebSocket - Opening a connection to a non-existent server or a stopped server generates an error but maintains the CONNECTING state indefinitely so it is not possible to close the connection or reopen it if you are cheking the state is not CONNECTING or OPEN.

Reproducible By

import { ErrorEvent } from "undici-types";

let webSocket: WebSocket;

function openConnection() {
    if (webSocket && webSocket.readyState <= WebSocket.OPEN) {
        console.log("WebSocket state: " + webSocket.readyState);
        return;
    }

    webSocket = new WebSocket("ws://localhost:1");
    console.log("WebSocket created");

    webSocket.addEventListener("error", (event) => handleError(event));
}

function handleError({ message }: ErrorEvent) {
    console.log(message);

    if (message === "Connection was closed before it was established.") {
        openConnection();
        return;
    }

    webSocket.close();
}

openConnection();

Expected Behavior

Fire a error and change state to CLOSED.

Logs & Screenshots

WebSocket created
Received network error or non-101 status code.
Connection was closed before it was established.
WebSocket state: 0

Environment

$ uname -a
Linux desktop 6.10.3-arch1-2 #1 SMP PREEMPT_DYNAMIC Tue, 06 Aug 2024 07:21:19 +0000 x86_64 GNU/Linux
$ node --version
v20.17.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions