amphp/websocket-client
Async WebSocket client for PHP built on Amp. Connect to ws/wss endpoints with fiber-friendly concurrency, consume realtime APIs, test WebSocket servers, and support custom handshakes, headers, heartbeats, and rate limits.
Start by installing the package via Composer (composer require amphp/websocket-client) and ensure Amp is initialized with Amp\Loop::run(). The core usage involves creating a client, connecting to a WebSocket server (e.g., ws://localhost:8080/chat), and handling messages via yield $client->receive(). A minimal example:
use Amp\Loop;
use Amp\Websocket\Client as Websocket;
Loop::run(function () {
$client = yield Websocket\connect('ws://echo.websocket.org');
yield $client->send('Hello, server!');
while ($message = yield $client->receive()) {
echo "Received: {$message->getData()}\n";
if ($message->isClose()) {
yield $client->close();
break;
}
}
});
First look at Client::connect() and the Message/Frame types. The examples/ directory (if included) demonstrates ping/pong, binary transfer, and TLS (wss://) use cases.
Amp\call() or async() functions to integrate WebSocket interaction into async workflows (e.g., fetching data via HTTP and subscribing to real-time updates).yield $client->send($frame) as a suspension point to respect client-side buffer limits—ideal for streaming large payloads without memory overflow.onOpen, onMessage, onClose callbacks registered on the Client. Example:
$client = yield Websocket\connect('wss://api.example.com/ws', [
'onOpen' => function (Websocket $client) { /* auth token here */ },
'onMessage' => fn($msg) => $this->handleTradeUpdate($msg),
'onClose' => fn($code, $reason) => $this->reconnect($code),
]);
amphp/http-server to build WebSocket bridges for HTTP clients (e.g., proxy requests to SSE/WS endpoints).try {} catch (\Throwable $e) {} and trigger reconnect loops (e.g., with Amp\TimeoutException handling for reconnect backoff).sleep(), fgets(), or synchronous cURL call inside Loop::run() will stall the event loop—always use Amp’s async utilities (Amp\delay() instead of sleep()).wss:// connections auto-verify TLS by default. Override via 'verify_peer' => false in connection options—only for dev/test (not production!).Client instances for multiplexed streams, but ensure close() is called gracefully (check isClose() on received messages) to avoid socket leaks.Websocket\frame($binaryData, Websocket\Frame::BINARY)—remember to inspect $frame->getOpcode() on receive.Amp\Loop::setLogger()) to trace events like connect, frame, close.frame->frame() construction—always use factory methods like Websocket\text()/Websocket\binary().How can I help you explore Laravel packages today?