Skip to content

PAM Socket

PAM serves WebSockets from the same native listener as HTTP. pushinbr/pam-socket gives you an event API on top of it: authenticate the handshake, register handlers per connection, join rooms, acknowledge messages and broadcast across workers through Redis Streams or NATS.

$io = Pam\Socket\Server::create();
$io->on('connection', static function (Pam\WS\Socket $socket): void {
$socket->emit('ready', ['id' => $socket->id]);
});
Terminal window
pam composer require pushinbr/pam-socket

For a new project, pam init realtime-api --template api --socket adds the package for you. The package requires PHP 8.4 and checks during construction that it runs inside a PAM runtime with the WebSocket capability; outside PAM it throws immediately.

Register the socket server next to your HTTP application in the same entry file:

index.php
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Pam\App;
use Pam\Http\Request;
use Pam\Http\Response;
use Pam\Socket\Server;
use Pam\WS\Acknowledgement;
use Pam\WS\Socket;
$io = Server::create();
$io->auth(static fn (array $context): bool =>
($context['headers']['authorization'] ?? null) === 'Bearer ' . getenv('SOCKET_TOKEN'));
$io->on('connection', static function (Socket $socket, array $context) use ($io): void {
$socket->join('lobby');
$socket->emit('ready', ['id' => $socket->id]);
$socket->on('chat.send', static function (mixed $data, Acknowledgement $ack) use ($io, $socket): void {
$ack->send(['received' => true]);
$io->to('lobby')->emit('chat.message', ['from' => $socket->id, 'body' => (string) ($data['body'] ?? '')]);
});
$socket->on('disconnect', static function () use ($socket): void {
error_log("socket {$socket->id} left");
});
});
$app = new App();
$app->get('/', static fn (Request $request, Response $response): Response => $response->json(['ok' => true]));
$app->listen((int) (getenv('PAM_PORT') ?: 3000));

Clients connect to the /ws path of the same host and port:

client.js
const ws = new WebSocket('ws://127.0.0.1:3000/ws');
ws.onmessage = (event) => console.log(JSON.parse(event.data));
ws.onopen = () => ws.send(JSON.stringify({ event: 'chat.send', id: 7, data: { body: 'Hi Alice' } }));

The client receives:

{"event":"ready","data":{"id":"socket-1"}}
{"ack":"7","data":{"received":true}}
{"event":"chat.message","data":{"body":"Hi Alice","from":"socket-1"}}

Every frame is a JSON text message.

Direction Shape Meaning
Client to server {"event": "name", "data": ..., "id": 7} Call the handler registered for name. id (string or integer) is optional and enables an acknowledgement.
Server to client {"event": "name", "data": ...} An event emitted to this socket, a room or everyone.
Server to client {"ack": "7", "data": ...} The acknowledgement for message 7.

Binary frames go to the socket’s binary handler. Messages without a matching handler, or handlers that throw, produce an error event with the message The WebSocket event failed. (the real message is logged; set the exposeErrors listener option only in development to send it).

auth() registers one authenticator that runs before the connection handler. It receives the handshake context and returns true to accept or false to close the connection:

Key Contents
headers Request headers as a name => value array with lowercase names.
query The raw query string, for example token=abc&room=1.
path The request path (/ws).
sessionId The socket’s ID.
resumeToken A signed resume token, present when websocketResumeSecret is configured.
$io->auth(static function (array $context) use ($tokens): bool {
parse_str($context['query'], $query);
return is_string($query['token'] ?? null) && $tokens->verify($query['token']) !== null;
});

Authenticate before registering privileged handlers or joining rooms. The transport also rejects browser handshakes from foreign origins; configure allowed origins with the websocketOrigins listener option (or PAM_WEBSOCKET_ORIGINS), which falls back to corsOrigins.

Server::on() accepts only the connection event. Its handler receives the Pam\WS\Socket and the handshake context. Register per-connection handlers on the socket:

Handler Signature
$socket->on('any.event', ...) function (mixed $data, Acknowledgement $ack): void
$socket->on('binary', ...) function (string $bytes): void
$socket->on('disconnect', ...) function (): void

Call $ack->send($data) to answer a message that carried an id. It sends at most once and does nothing when the client did not ask for an acknowledgement.

$socket->emit('profile.updated', ['name' => 'Alice']); // this socket
$socket->emitBinary($pngBytes); // this socket, binary frame
$io->to('project:42')->emit('project.updated', ['id' => 42]); // everyone in a room
$io->emit('maintenance', ['in' => 300]); // every connected socket
$socket->close('kicked by moderator');

data can be any JSON-serializable value.

$socket->join('project:42');
$socket->leave('project:42');

Room names are arbitrary non-empty strings. A socket leaves every room when it disconnects. Room membership lives in the worker that owns the connection; use an adapter so room emits reach sockets on other workers and nodes.

With more than one worker, each socket lives in one process. Register an adapter so broadcasts and room emits are published to every worker:

use Pam\WS\NatsAdapter;
use Pam\WS\RedisStreamsAdapter;
$io->adapter(new RedisStreamsAdapter(host: '127.0.0.1', port: 6379, stream: 'pam:ws'));
// or
$io->adapter(new NatsAdapter(host: '127.0.0.1', port: 4222, subject: 'pam.ws'));
Adapter Notable options
RedisStreamsAdapter host, port (6379), stream (pam:ws), timeout, username, password, database, tls, maxRetries (3), maxStreamLength (100,000). Requires the redis extension.
NatsAdapter host, port (4222), subject (pam.ws), timeout, tls, token, username, password, maxRetries (3), maxMessageBytes (8 MiB).
InMemoryAdapter capacity (10,000). Single process only; useful in tests.

Implement Pam\WS\Adapter (publish(string $channel, string $payload) and poll(): iterable) for another broker. An adapter coordinates live delivery; it is not durable storage.

Set a resume secret of at least 32 bytes in the listener options. Each connection then receives a signed resumeToken, exposed as $socket->resumeToken:

index.php
$io->on('connection', static function (Socket $socket): void {
$socket->emit('session', ['sessionId' => $socket->id, 'resumeToken' => $socket->resumeToken]);
});
$app->listen(3000, '127.0.0.1', [
'websocketResumeSecret' => getenv('WEBSOCKET_RESUME_SECRET'),
'websocketResumeTtlSeconds' => 86_400,
]);

After a disconnect, the client reconnects to /ws?sessionId=...&resumeToken=... and keeps the same socket ID. An invalid or expired token is rejected with 401. Rooms and handlers are registered again by your connection handler, and events emitted while the client was away are not replayed. Persist domain events when missed messages matter. Rotating the secret invalidates every resume token.

WebSocket limits are part of the listener options:

Option Default Description
websocketMaxConnections 10000 Concurrent connections; further upgrades get 503.
websocketMaxMessageBytes 1048576 Largest inbound message.
websocketQueueCapacity 256 Outbound frames queued per connection.
websocketHeartbeatMs 15000 Ping interval.
websocketTimeoutMs 45000 Close a connection that has been silent this long.
websocketCompression true Per-message deflate.
websocketOrigins [] Allowed browser origins (falls back to corsOrigins).
websocketResumeSecret unset Enables signed resume tokens; at least 32 bytes.
websocketResumeTtlSeconds 86400 Resume token lifetime.

Rooms, acknowledgements and resume tokens help realtime features, but they do not give exactly-once delivery. For actions that matter:

  • give each command a stable ID and make handlers idempotent;
  • persist state before acknowledging;
  • store events you may need to replay, and reconnect after deploys and worker reloads.

Treat every event name and payload as public input: validate it, authorize each referenced resource, keep messages small and never send exception details to clients. In a Laravel host, socket callbacks share the single Laravel execution slot of each worker; scale with more workers. See also WebSockets.

Type Members
Pam\Socket\Server static create(), on('connection', callable), auth(callable), emit(string $event, mixed $data = null), to(string $room): RoomEmitter, adapter(Adapter); readonly server (the native Pam\WS\Server)
Pam\WS\Socket Readonly id, resumeToken; on(), emit(), emitBinary(), join(), leave(), close(string $reason = 'closed by application')
Pam\WS\Acknowledgement send(mixed $data = null)
Pam\WS\RoomEmitter emit(string $event, mixed $data = null)
Pam\WS\Adapter publish(), poll()

pushinbr/pam-socket requires pushinbr/pam-contracts ^1.0 and is licensed under the Apache License 2.0.