WebConnect

A WebSocket connection wrapper for sending, receiving and observing structured real-time messages.

Import
the javascript logo
import { WebConnect } from "@schukai/monster/source/net/webconnect.mjs";
Source
the git logo
Package
the npm logo
Since
3.1.0

Introduction

WebConnect wraps a browser WebSocket connection with Monster-style options, reconnect behaviour and an observable receive queue.

Core Responsibilities

SurfaceWhat it solves
connect()Creates the socket connection using the configured url and timeout rules.
send()Sends structured messages through the active socket.
poll(), peek()Consume or inspect received messages from the queue.
attachObserver()React when new messages arrive in the queue.
close()Manually close the connection without triggering reconnect loops.

Where It Fits

Use it for dashboards, collaborative tools, chat-like traffic and server push flows. For classic request/response data access, stay on datasource or REST abstractions.

Connect And Consume Structured Messages

import { WebConnect } from "@schukai/monster/source/net/webconnect.mjs";
import { Message } from "@schukai/monster/source/net/webconnect/message.mjs";

const output = document.getElementById("webconnect-output");
const webconnect = new WebConnect({ url: "wss://example.invalid/socket" });

document.getElementById("webconnect-run").addEventListener("click", () => {
    const message = new Message({
        type: "status",
        payload: {
            connected: true,
            channel: "demo",
        },
    });

    output.textContent = JSON.stringify(
        {
            readyStateConnected: webconnect.isConnected(),
            nextMessage: message.toJSON(),
        },
        null,
        2,
    );
});
Open in playground

Send Structured Messages And Close The Connection Manually

import { WebConnect } from "@schukai/monster/source/net/webconnect.mjs";
import { Message } from "@schukai/monster/source/net/webconnect/message.mjs";

const output = document.getElementById("webconnect-send-close-output");
const OriginalWebSocket = window.WebSocket;

class FakeWebSocket {
    constructor(url) {
        this.url = url;
        this.readyState = 0;
        setTimeout(() => {
            this.readyState = 1;
            this.onopen?.();
        }, 0);
    }

    send(data) {
        this.lastSent = data;
    }

    close(code = 1000, reason = "") {
        this.readyState = 3;
        this.onclose?.({ code, reason });
    }
}

window.WebSocket = FakeWebSocket;

document.getElementById("webconnect-send-close-run").addEventListener("click", async () => {
    const webconnect = new WebConnect({ url: "wss://example.invalid/socket" });
    await webconnect.connect();
    await webconnect.send(new Message({ type: "ping", payload: { ok: true } }));
    await webconnect.close(1000, "demo-finished");

    output.textContent = JSON.stringify({
        connectedBeforeClose: true,
        sent: webconnect.isConnected() ? "unexpected" : "structured message sent before close",
    }, null, 2);
});

window.addEventListener("pagehide", () => {
    window.WebSocket = OriginalWebSocket;
}, { once: true });
Open in playground

Observe Incoming Queue Updates Through The Receive Queue Observer API

import { WebConnect } from "@schukai/monster/source/net/webconnect.mjs";
import { Observer } from "@schukai/monster/source/types/observer.mjs";

const output = document.getElementById("webconnect-observer-output");
const OriginalWebSocket = window.WebSocket;

class FakeWebSocket {
    constructor() {
        this.readyState = 0;
        setTimeout(() => {
            this.readyState = 1;
            this.onopen?.();
            this.onmessage?.({ data: JSON.stringify({ type: "status", payload: { phase: "ready" } }) });
        }, 0);
    }

    send() {}
    close() {
        this.readyState = 3;
        this.onclose?.({ code: 1000, reason: "" });
    }
}

window.WebSocket = FakeWebSocket;

document.getElementById("webconnect-observer-run").addEventListener("click", async () => {
    const webconnect = new WebConnect({ url: "wss://example.invalid/socket" });
    webconnect.attachObserver(new Observer(function () {
        const next = webconnect.peek();
        output.textContent = JSON.stringify({
            queued: webconnect.dataReceived(),
            next: next?.toJSON?.() ?? null,
        }, null, 2);
    }));
    await webconnect.connect();
});

window.addEventListener("pagehide", () => {
    window.WebSocket = OriginalWebSocket;
}, { once: true });
Open in playground

Configure Reconnect And Timeout Options For Resilient Connections

import { WebConnect } from "@schukai/monster/source/net/webconnect.mjs";

document.getElementById("webconnect-options-run").addEventListener("click", () => {
    const webconnect = new WebConnect({
        url: "wss://example.invalid/socket",
        connection: {
            timeout: 8000,
            reconnect: {
                enabled: true,
                attempts: 4,
                timeout: 1500,
            },
        },
    });

    document.getElementById("webconnect-options-output").textContent = JSON.stringify({
        url: webconnect.getOption("url"),
        timeout: webconnect.getOption("connection.timeout"),
        reconnectEnabled: webconnect.getOption("connection.reconnect.enabled"),
        reconnectAttempts: webconnect.getOption("connection.reconnect.attempts"),
        reconnectTimeout: webconnect.getOption("connection.reconnect.timeout"),
    }, null, 2);
});
Open in playground

Exported

WebConnect

Derived from

BaseWithOptions

Options

The Options listed in this section are defined directly within the class. This class is derived from several parent classes. Therefore, it inherits Options from these parent classes. If you cannot find a specific Options in this list, we recommend consulting the documentation of the BaseWithOptions.

Option
Type
Default
Description
url
string
undefined
source that you wish to fetch.
object
connection
connection.timeout
object
5000
the connection.
connection.reconnect.timeout
number
1000
The timeout in milliseconds for the reconnect.
connection.reconnect.attempts
number
1
The maximum number of reconnects.
connection.reconnect.enabled
boolean
false
If the reconnect is enabled.

Properties

The Properties listed in this section are defined directly within the class. This class is derived from several parent classes. Therefore, it inherits Properties from these parent classes. If you cannot find a specific Properties in this list, we recommend consulting the documentation of the BaseWithOptions.

Methods

The methods listed in this section are defined directly within the class. This class is derived from several parent classes. Therefore, it inherits methods from these parent classes. If you cannot find a specific method in this list, we recommend consulting the documentation of the BaseWithOptions.

Constructor

constructor([options])
Parameters
  • [options] {object}: options contains definitions for the webconnect.

Behavioral methods

close([code=1000],[reason=""])
Parameters
  • [code=1000] {number}: The close code.
  • [reason=""] {string}: The close reason.
Returns
  • {Promise}
This method closes the connection.

State query methods

isConnected()
Returns
  • {boolean}

Static methods

[instanceSymbol]()
Returns
  • {symbol}
This method is called by the instanceof operator.

Other methods

attachObserver(observer)
Parameters
  • observer {observer}: observer
Returns
  • {ProxyObserver}
Attach a new observer
connect()
Returns
  • {Promise}
containsObserver(observer)
Parameters
  • observer {observer}: observer
Returns
  • {boolean}
dataReceived()
Returns
  • {boolean}
Are there any messages in the receive queue?
detachObserver(observer)
Parameters
  • observer {observer}: observer
Returns
  • {ProxyObserver}
Detach a observer
peek()
Returns
  • {Object}
Get Message from the receive queue, but do not remove it.
poll()
Returns
  • {Message}
Polls the receive queue for new messages.
send(message)
Parameters
  • message {message|object}: message
Returns
  • {Promise}

Events

This component does not fire any public events. It may fire events that are inherited from its parent classes.

The current width of the area is too small to display the content correctly.