DocumentationCore Protocol

Connection Lifecycle

PaindaProtocol is designed to keep connections alive and seamlessly reconnect when clients drop. This page explains the standard lifecycle from connecting to disconnecting.

1. Handshake (No HTTP Polling)

Unlike other frameworks, PaindaProtocol does not start with a 3 RTT (Round Trip Time) HTTP polling phase. It attempts to open a pure WebSocket connection immediately.

import { PPClient } from "@painda/client";

// This immediately attempts a ws:// or wss:// connection
const client = new PPClient("ws://localhost:7000");

client.on("connect", () => {
  console.log("Connected directly! Id:", client.id);
});

2. Automatic Reconnects

In the real world, connections drop (e.g. driving through a tunnel on mobile, or server restarts). PaindaProtocol manages these drops automatically.

Reconnect Configuration

reconnect: boolean - Enable/disable auto-reconnect (default: true).

reconnectAttempts: number - Max attempts before giving up (default: Infinity).

reconnectDelay: number - Base delay in milliseconds (default: 1000).

const client = new PPClient("wss://api.example.com", {
  reconnect: true,
  reconnectDelay: 2000,
});

client.on("disconnect", (reason) => {
  console.log("Disconnected:", reason); // e.g. "transport close"
});

client.on("reconnect", (attempt) => {
  console.log(`Successfully reconnected on attempt ${attempt}`);
});

3. Reconnect Strategy: Jitter + Backoff

When a server restarts, and 1000 clients attempt to reconnect immediately at exactly 1000ms, your server will be DDOSed by your own users (Thundering Herd Problem).

PaindaProtocol adds random Jitter (typically ±20%) to the reconnectDelay. It also supports Backoff. If attempt 1 fails at ~1000ms, attempt 2 might happen at ~2000ms, then ~4000ms, until maxing out at a sensible upper bound.

4. The Offline Buffer

What happens if you emit a message while disconnected?

// Client is currently OFFLINE
client.emit("scoreUpdate", { points: 10 });

PaindaProtocol pushes this message into an internal Offline Buffer. As soon as the "reconnect" event fires, it automatically flashes the buffer to the server in order.

State Recovery

If you want to gracefully recover disconnected sessions (resume missed messages while disconnected), pair the basic lifecycle with the `@painda/recovery` or `@painda/persistence` Middleware on your Server!