WebSocket Class
The WebSocket class provides a robust, fully-featured interface for establishing and managing WebSocket connections with the Pterodactyl panel (or any WebSocket endpoint). It wraps the native WebSocket API and adds advanced features such as:
Written By Cptcr
Last updated 12 months ago
Automatic reconnection with multiple strategies (fixed, exponential, exponential-jitter)
Fallback URL support
Heartbeat (ping/pong) mechanism with latency tracking
Message queuing when the connection is down
Outgoing/incoming interceptors (middleware)
Auto‑JSON handling (stringify/parse)
Rich event system with hooks for custom behaviors
A helper for request/response patterns
Connection metrics
This class is designed to be beginner-friendly while offering advanced configuration options for power users.
Table of Contents
Features
Installation
Install the package via npm:
npm install pterodactyl-api-wrapper
Ensure your project is configured for TypeScript with the appropriate tsconfig.json settings.
Usage Example
import { WSConnectionOptions, AdvancedWebSocket as WebSocket, WSMetrics } from "pterodactyl-api-wrapper";
const options: WSConnectionOptions = {
url: "wss://panel.example.com/api/client/servers/123/ws",
autoReconnect: true,
reconnectStrategy: "exponential-jitter",
reconnectInterval: 1000,
maxReconnectAttempts: 5,
connectionTimeout: 10000,
heartbeatInterval: 30000,
heartbeatTimeout: 5000,
queueMessages: true,
autoJson: true,
logger: (level, ...args) => console.log(`[WS ${level.toUpperCase()}]`, ...args),
};
const ws = new WebSocket(options);
ws.connect()
.then((socket) => {
console.log("Connected to WebSocket:", socket);
ws.send({ action: "ping" })
.then(() => console.log("Ping sent"))
.catch((err) => console.error("Error sending ping:", err));
})
.catch((err) => console.error("Failed to connect WebSocket:", err));
ws.addEventListener("message", (event) => {
console.log("Received message:", event.data);
});
Configuration Options
Method Reference
connect()
send(data: any)
sendAndWaitResponse()
manualReconnect()
close()
isConnected() / getConnectionState()
getMetrics()
updateOptions()
clearMessageQueue()
destroy()
Event Management
The WebSocket class features a custom event system with the following events:
Use the following methods to manage events:
Example Code
Below is a comprehensive example that demonstrates the full capabilities of the WebSocket class:
import { WSConnectionOptions, AdvancedWebSocket as WebSocket, WSMetrics } from "pterodactyl-api-wrapper";
const options: WSConnectionOptions = {
url: "wss://panel.example.com/api/client/servers/123/ws",
autoReconnect: true,
reconnectStrategy: "exponential-jitter",
reconnectInterval: 1000,
maxReconnectAttempts: 5,
connectionTimeout: 10000,
heartbeatInterval: 30000,
heartbeatTimeout: 5000,
queueMessages: true,
autoJson: true,
logger: (level, ...args) => console.log(`[WS ${level.toUpperCase()}]`, ...args),
};
const ws = new WebSocket(options);
// Connect to the WebSocket
ws.connect()
.then((socket) => {
console.log("Connected to WebSocket:", socket);
// Listen for messages
ws.addEventListener("message", (event) => {
console.log("Received message:", event.data);
});
// Send a ping message and wait for the pong response
ws.sendAndWaitResponse({ action: "ping" }, (msg) => msg.action === "pong", 5000)
.then((response) => {
console.log("Received pong response:", response);
})
.catch((err) => {
console.error("Error waiting for pong response:", err);
});
})
.catch((err) => {
console.error("Failed to connect WebSocket:", err);
});
// Retrieve connection metrics after 60 seconds
setTimeout(() => {
const metrics: WSMetrics = ws.getMetrics();
console.log("Connection Metrics:", metrics);
}, 60000);
// Destroy the connection when done
// ws.destroy();