Star ✨ on GitHub

WebSocket

A custom WebSocket implementation that unifies behavior across Node.js and Bun environments, featuring automatic heartbeats and latency tracking.

The WebSocket class is an internal utility used by the Node class to communicate with Lavalink. It abstracts away the differences between Node.js native http/https requests and Bun's native WebSocket implementation.

Constructor

new WebSocket(url, options)

Creates a new WebSocket connection.

urlstring required

The URL to connect to.

optionsobject

Connection options.

options

headersRecord<string, string>

Custom headers to send with the handshake.

Properties

WebSocket Properties

Connection state and metrics.

State

readyStatenumber

The current state of the connection (1 = Open, 3 = Closed).

latencynumber

The current round-trip latency in milliseconds.

Events

WebSocket Events

Events emitted by the socket during its lifecycle.

Lifecycle

openvoid

Emitted when the connection is established.

close{ code: number, reason: string }

Emitted when the connection is closed.

error{ error: Error }

Emitted when an error occurs.

Data & Debug

message{ data: string | Buffer }

Emitted when a message is received.

pingBuffer

Emitted when a ping frame is received.

pongnumber | void

Emitted when a pong frame is received.

debugstring

Emitted for debug logs (Node.js only).

Methods

send(data)

Sends data to the WebSocket server.

datastring | Buffer required

The data to send.

Example
ws.send(JSON.stringify({ op: "ping" }));

close(code, reason)

Closes the WebSocket connection.

codenumber

Status code (default: 1000).

reasonstring

Reason for closing.

Example
ws.close(1000, "Normal closure");

ping(data)

ping(data)#

Sends a ping frame and waits for a pong. Returns the latency in milliseconds. Note: Not supported in Bun environments.

datastring | Buffer

Optional payload for the ping.

Example
const latency = await ws.ping();
console.log(`Latency: ${latency}ms`);

on(event, listener)

Adds a listener for the specified event. Inherited from EventEmitter.

eventstring required

The event name.

listenerFunction required

The callback function.

Example
ws.on("message", (msg) => console.log(msg));

once(event, listener)

Adds a one-time listener for the specified event. Inherited from EventEmitter.

eventstring required

The event name.

listenerFunction required

The callback function.

Example
ws.once("open", () => console.log("Connected!"));

off(event, listener)

Removes a listener for the specified event. Inherited from EventEmitter.

eventstring required

The event name.

listenerFunction required

The callback function to remove.

emit(event, ...args)

Synchronously calls each of the listeners registered for the event. Inherited from EventEmitter.

eventstring required

The event name.

...argsany[]

Arguments to pass to the listeners.