DocumentationCore Protocol

Namespaces

Namespaces let you split your application logic over a single WebSocket connection. Each namespace has its own event handlers, middleware, and rooms.

Server

import { PPServer } from "@painda/core";

const server = new PPServer({ port: 3000 });

// Default namespace "/"
server.on("connection", (client) => {
  console.log("Client joined default namespace");
});

// Custom namespace "/admin"
const admin = server.of("/admin");

// Namespace-specific middleware
admin.use((socket, next) => {
  if (isAdmin(socket)) next();
  else next(new Error("Forbidden"));
});

admin.on("connection", (nsSocket) => {
  nsSocket.on("stats", (msg) => {
    nsSocket.send({ type: "stats", payload: getStats() });
  });
});

// Custom namespace "/game"
const game = server.of("/game");
game.on("connection", (nsSocket) => {
  nsSocket.on("move", (msg) => {
    // Broadcast to all in this namespace
    game.broadcast(msg, nsSocket.id);
  });
});

Client

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

const client = new PPClient({ url: "ws://localhost:3000" });

// Send to a specific namespace
client.send(
  { type: "stats", payload: {} },
  { namespace: "/admin" }
);

// Default namespace
client.send({ type: "chat", payload: "Hello" });

Next: Middleware Pipeline