CKN Technology Core · Socket Extensions

CKN Technology Core
Socket Extensions

Socket is a wrapper class around WebSocket that provides simplified connection handling, async event callbacks, optional queued message receiving, safe connect/send/close operations, and automatic JSON serialization for outbound data. It is part of the CKN Framework Communication Module.

Class: Socket – Constructor

constructor(url)

Description
Creates a new socket instance and stores the WebSocket URL. The instance will lazily open the connection when connect() is called, and it keeps an internal reference to the underlying WebSocket object.

Parameters

  • url – WebSocket server URL (e.g. "wss://example.com/ws").

Signature

constructor(url: string)

Example

import { Socket } from "@ckn-technology/core";

const socket = new Socket("wss://example.com/ws");

Public Events & Properties

enableDataQueue

Description
Boolean flag that controls whether incoming messages should be placed into an internal queue. When set to true, all received messages are stored and can be consumed via receive(). When false, messages are only delivered via onReceived callback.

Default: false

Example

const socket = new Socket("wss://example.com/ws");
socket.enableDataQueue = true;

onStateChanged

Description
Optional async callback invoked whenever the connection state changes. Receives a single boolean argument:

  • true – WebSocket is connected.
  • false – WebSocket is disconnected/closed.

Signature
(state: boolean) => Promise<void>

Example

socket.onStateChanged = async (state) => {
    console.log("Socket state:", state ? "connected" : "disconnected");
};

onConnected

Description
Optional async callback executed when the WebSocket connection is successfully opened.

Signature
() => Promise<void>

Example

socket.onConnected = async () => {
    console.log("Socket connected!");
};

onReceived

Description
Optional async callback invoked for each message received from the server, in addition to data being added to queue when enableDataQueue is true.

Signature
(data: any) => Promise<void>

Example

socket.onReceived = async (data) => {
    console.log("Received message:", data);
};

onClosed

Description
Optional async callback executed when the WebSocket connection is closed (normally or due to error).

Signature
() => Promise<void>

Example

socket.onClosed = async () => {
    console.log("Socket closed!");
};

Methods (Overridable)

async connect()

Description
Initializes the WebSocket connection and binds all internal event handlers. If the socket is already connected, it throws an error to prevent multiple concurrent connections using the same instance.

Behavior

  • Creates a new WebSocket instance using the URL supplied in the constructor.
  • Registers:
    • onopen – triggers onConnected and onStateChanged(true).
    • onmessage – pushes data to internal queue if enableDataQueue is true, and calls onReceived.
    • onclose – invokes onClosed and onStateChanged(false).

Signature

connect(): Promise<void>

Example

const socket = new Socket("wss://example.com/ws");
await socket.connect();

async send(data)

Description
Sends data through the socket to the server. The method ensures that the socket is connected and automatically serializes non-string payloads as JSON.

Behavior

  • Throws an error if the internal WebSocket is not yet connected.
  • If data is not a string, it is serialized with JSON.stringify.
  • Uses underlying WebSocket.send to transmit the data.

Signature

send(data: any): Promise<void>

Example

await socket.send({ type: "ping" });

async receive(intervalTimeListening = 500)

Description
Retrieves a single message from the internal queue. This is useful when you want controlled message consumption instead of pure event-driven streaming.

Requirements

  • enableDataQueue must be set to true.
  • The socket must be connected.

Behavior

  • If intervalTimeListening > 0, the method waits until a new item appears in the queue, polling or awaiting internal state.
  • If intervalTimeListening === 0, it returns the next item immediately (or null/undefined if queue is empty).

Signature

receive(intervalTimeListening?: number): Promise<any>

Example

socket.enableDataQueue = true;

const msg = await socket.receive();  // waits for next message by default
console.log("Received:", msg);

async close()

Description
Closes the WebSocket connection safely and resets internal state, preventing memory leaks or redundant callbacks.

Behavior

  • Closes the internal WebSocket instance (if any).
  • Clears event callbacks and the message queue.
  • Marks the socket instance as disconnected and ready to be reconnected if desired.

Signature

close(): Promise<void>

Example

await socket.close();

Typical Usage Flow

A typical end-to-end usage scenario looks like this:

import { Socket } from "@ckn-technology/core";

const socket = new Socket("wss://example.com/ws");

socket.onConnected = async () => {
    console.log("Connected!");
};

socket.onReceived = async (msg) => {
    console.log("Message:", msg);
};

socket.onClosed = async () => {
    console.log("Socket closed");
};

await socket.connect();
await socket.send({ hello: "world" });

socket.enableDataQueue = true;
const nextMessage = await socket.receive();
console.log("Queued:", nextMessage);

await socket.close();

Notes

  • All callback handlers (onConnected, onReceived, onClosed, onStateChanged) are fully async-compatible.
  • Message receiving supports both real-time, event-based streaming (via onReceived) and queued processing (via receive() when enableDataQueue is enabled).
  • Helps standardize WebSocket interactions across the CKN Framework by providing a common contract for connect, send, receive, and close operations.

Summary

The Socket class provides a robust and standardized interface for WebSocket communication within the CKN Framework. It simplifies common interactions such as connecting, sending, receiving, and closing, while offering async event callbacks and optional queued message processing.

By combining real-time streaming via onReceived with queue-based consumption using receive(), it gives developers the flexibility to implement both push-style and pull-style message handling patterns. Automatic JSON serialization for outbound data and consistent error handling help reduce boilerplate and enforce a clean, predictable WebSocket usage pattern across all CKN applications.