Client: Setup & Configuration
MeshClient manages the WebSocket connection to your Mesh server. It handles reconnects, pings, latency, and command dispatching.
Basic usage
import { MeshClient } from "@mesh-kit/core/client";
const client = new MeshClient("ws://localhost:8080");
await client.connect();
const res = await client.command("echo", "Hello!");
console.log(res); // "echo: Hello!"
Configuration options
The second argument to MeshClient
is optional and lets you control reconnect behavior and liveness settings:
const client = new MeshClient("ws://localhost:8080", {
shouldReconnect: true, // default: true
reconnectInterval: 2000, // ms between attempts (default: 2000)
maxReconnectAttempts: Infinity,
pingTimeout: 30000, // ms to wait for pings (default: 30000)
maxMissedPings: 1, // allowed missed pings before reconnecting
});
💡
These options should match the server’s configured pingInterval
and maxMissedPongs
values to avoid premature disconnects.
Connect / Disconnect
You must call connect()
manually to start the WebSocket connection.
const client = new MeshClient("ws://localhost:8080");
await client.connect(); // Connect
await client.close(); // Disconnect (and disable auto-reconnect)
Events
The client emits events for connection state:
client.on("connect", () => {
console.log("Connected");
});
client.on("close", () => {
console.log("Connection closed");
});
client.on("reconnect", () => {
console.log("Reconnected");
});
client.on("reconnectfailed", () => {
console.log("Gave up trying to reconnect");
});
client.on("latency", (ms) => {
console.log(`Latency: ${ms}ms`);
});
Or use the shorthand methods:
client.onConnect(() => {
console.log("Connected to server");
});
client.onDisconnect(() => {
console.log("Disconnected from server");
});
client.onReconnect(() => {
console.log("Reconnected to server");
});
client.onReconnectFailed(() => {
console.log("Failed to reconnect after maximum attempts");
});
Reconnection behavior
If shouldReconnect
is enabled and a ping is missed:
- The client disconnects
- Mesh attempts to reconnect
- On success, emits
"reconnect"
- On failure (after
maxReconnectAttempts
), emits"reconnectfailed"
Connection status
Check current status via:
import { Status } from "@mesh-kit/core/client";
if (client.status === Status.ONLINE) {
console.log("Connected");
}
Command timeout
By default, client.command(...)
times out after 30s. You can override per-call:
const result = await client.command("echo", "hi", 10_000); // 10s timeout
Next steps:
Last updated on