Skip to content

WebSockets

PAM serves WebSockets from the same port as your HTTP application. The Rust layer accepts the upgrade at /ws, keeps the connection alive with heartbeats, applies limits and compression, and calls your PHP handlers only when something happens: a client connects, sends an event, sends binary data or leaves.

The API is event-oriented. Clients send JSON objects with an event name and data; you register a handler per event, reply with emit(), group sockets into rooms, and confirm messages with acknowledgements.

The fastest way to start is a project with socket support:

Terminal window
pam init realtime-api --template api --socket
cd realtime-api
pam dev index.php

Or add the package to an existing application:

Terminal window
pam composer require pushinbr/pam-socket

pushinbr/pam-socket provides Pam\Socket\Server, a thin wrapper that checks the runtime supports WebSockets and forwards to the built-in Pam\WS\Server. Both expose the same methods, so you can also use the runtime class directly:

index.php
<?php
declare(strict_types=1);
use Pam\WS\Socket;
/** @var \Nimbus\App $app */
$app = require __DIR__ . '/bootstrap/app.php';
$socket = \Pam\Socket\Server::create();
$socket->on('connection', static function (Socket $client): void {
$client->emit('welcome', ['message' => 'Connected to Pam Socket']);
});
$app->listen((int) (getenv('PAM_PORT') ?: 3000));

Register socket handlers before listen(). Clients connect to ws://host:port/ws (or wss:// behind TLS).

Clients send UTF-8 JSON text frames:

{"event": "chat", "data": {"text": "hi"}, "id": 7}

event is required, data is optional and id (a string or integer) asks for an acknowledgement. The server sends events as {"event": ..., "data": ...} and acknowledgements as {"ack": "<id>", "data": ...}.

A complete chat server:

index.php
<?php
declare(strict_types=1);
use Pam\Http\Request;
use Pam\Http\Response;
use Pam\Http\Server;
use Pam\WS\Acknowledgement;
use Pam\WS\Server as Sockets;
use Pam\WS\Socket;
$io = new Sockets();
$io->auth(static function (array $context): bool {
parse_str($context['query'], $query);
return hash_equals('secret-token', (string) ($query['token'] ?? ''));
});
$io->on('connection', static function (Socket $socket, array $context) use ($io): void {
$socket->join('lobby');
$socket->emit('welcome', ['id' => $socket->id]);
$socket->on('chat', static function (mixed $data, Acknowledgement $ack) use ($io): void {
$io->to('lobby')->emit('chat', ['text' => (string) ($data['text'] ?? '')]);
$ack->send(['stored' => true]);
});
$socket->on('disconnect', static function () use ($socket): void {
error_log("socket {$socket->id} left");
});
});
Server::create(static fn (Request $request, Response $response): Response => $response->send('ok'))
->listen(3000, '127.0.0.1');
public/chat.js
const ws = new WebSocket('ws://127.0.0.1:3000/ws?token=secret-token');
ws.onopen = () => ws.send(JSON.stringify({ event: 'chat', data: { text: 'hi' }, id: 7 }));
ws.onmessage = (message) => console.log(message.data);

The client receives:

{"event":"welcome","data":{"id":"socket-1"}}
{"event":"chat","data":{"text":"hi"}}
{"ack":"7","data":{"stored":true}}
Method Description
on('connection', fn (Socket $socket, array $context)) The only server-level event. $context holds headers, query, path, sessionId and, when resume is enabled, resumeToken.
emit($event, $data = null) Broadcast to every connected socket
to($room)->emit($event, $data = null) Send to every socket in a room
auth(callable $authenticator) Accept or reject a connection before connection runs
adapter(Adapter $adapter) Share broadcasts across workers (see Adapters)
Method Description
$socket->id Server-assigned socket ID
on($event, $handler) Handle a client event. Handlers receive (mixed $data, Acknowledgement $ack). Two names are special: binary receives the raw bytes of a binary frame, and disconnect runs (with no arguments) when the socket closes.
emit($event, $data = null) Send an event to this socket
emitBinary(string $data) Send a binary frame
join($room) / leave($room) Manage room membership
close($reason = 'closed by application') Close the connection

Acknowledgement::send($data = null) replies once; further calls, or calls for a message without an id, do nothing.

If a handler throws, PAM logs the exception and sends the client an error event with the message The WebSocket event failed. (or the real message when exposeErrors is on). An event with no registered handler is reported the same way.

The authenticator receives the connection context and returns true to accept or false to close the socket with authentication rejected. It runs before your connection handler, so a rejected client never reaches your event handlers.

$io->auth(static function (array $context) use ($tokens): bool {
$header = $context['headers']['authorization'] ?? '';
return str_starts_with($header, 'Bearer ')
&& $tokens->isValid(substr($header, 7));
});

Browsers cannot set custom headers on a WebSocket, so browser clients usually pass a short-lived token in the query string or rely on a session cookie (available in $context['headers']['cookie']).

A browser on another site could otherwise open a socket carrying your user’s cookies. PAM rejects an upgrade with 403 when the Origin header is neither the request’s own host nor listed in websocketOrigins (when that list is empty, corsOrigins is used). Clients that send no Origin (servers, mobile apps) are not affected.

$server->listen(3000, '0.0.0.0', [
'websocketOrigins' => ['https://app.example.com'],
]);

PAM_WEBSOCKET_ORIGINS (comma separated), when set, takes precedence over the option, so you can change the list without touching code. * allows any origin. Origin checks are not authentication: always authenticate as well.

Rooms and broadcasts live in each worker’s memory. With pam start --workers N, a client connected to worker 1 does not see a broadcast emitted on worker 2 unless you install an adapter that relays messages:

Adapter Constructor (main arguments) Notes
Pam\WS\InMemoryAdapter capacity: 10_000 Single process; useful in tests
Pam\WS\RedisStreamsAdapter host, port: 6379, stream: 'pam:ws', password, database, tls, maxStreamLength: 100_000 Requires the redis PHP extension
Pam\WS\NatsAdapter host, port: 4222, subject: 'pam.ws', token, username, password, tls Speaks the NATS protocol directly
use Pam\WS\NatsAdapter;
$io->adapter(new NatsAdapter(host: 'nats.internal', subject: 'acme.ws'));

You can implement Pam\WS\Adapter yourself: it has publish(string $channel, string $payload): void and poll(): iterable.

An adapter relays live messages. It is not a durable queue: messages sent while a worker is down, or before a client reconnects, are lost. Persist events that must not be missed.

When you set websocketResumeSecret (at least 32 bytes, from a secret manager), PAM signs each connection’s session ID and passes sessionId and resumeToken in the connection context. A client that reconnects with ?sessionId=...&resumeToken=... keeps its socket ID; an invalid pair is refused with 401. Tokens expire after websocketResumeTtlSeconds (86400 by default), and rotating the secret invalidates them all.

Resuming restores the identity, not missed messages. Replay those from your own event log.

All options go in the listen() options array:

Option Default Description
websocketMaxConnections 10000 Connections per worker; extra upgrades get 503
websocketMaxMessageBytes 1048576 Largest inbound message
websocketQueueCapacity 256 Outbound messages buffered per socket
websocketHeartbeatMs 15000 Ping interval
websocketTimeoutMs 45000 Close a connection that stops answering
websocketCompression true permessage-deflate
websocketOrigins [] Allowed browser origins (see above)
websocketResumeSecret none Enables signed session resume
websocketResumeTtlSeconds 86400 Resume token lifetime

Watch pam_websocket_connections, pam_websocket_messages_total and pam_websocket_backpressure_total in /metrics.

During a zero-downtime reload, old workers drain and their sockets close. Clients must reconnect (with resume credentials if you use them). Design handlers to be idempotent and use a domain identifier when a retried event must not be applied twice.