Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Websocket Client Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

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.

Implementation Patterns

  • Compose with coroutines: Use Amp\call() or async() functions to integrate WebSocket interaction into async workflows (e.g., fetching data via HTTP and subscribing to real-time updates).
  • Backpressure handling: Use yield $client->send($frame) as a suspension point to respect client-side buffer limits—ideal for streaming large payloads without memory overflow.
  • Lifecycle events: Hook into connection events via 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),
    ]);
    
  • Integration with web servers: Combine with amphp/http-server to build WebSocket bridges for HTTP clients (e.g., proxy requests to SSE/WS endpoints).
  • Error recovery: Wrap client logic in try {} catch (\Throwable $e) {} and trigger reconnect loops (e.g., with Amp\TimeoutException handling for reconnect backoff).

Gotchas and Tips

  • Never use blocking I/O inside coroutines: Any 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()).
  • TLS verification: wss:// connections auto-verify TLS by default. Override via 'verify_peer' => false in connection options—only for dev/test (not production!).
  • Connection reuse caution: Reuse Client instances for multiplexed streams, but ensure close() is called gracefully (check isClose() on received messages) to avoid socket leaks.
  • Binary frames: Use Websocket\frame($binaryData, Websocket\Frame::BINARY)—remember to inspect $frame->getOpcode() on receive.
  • Debugging: Enable Amp’s loop logger (via Amp\Loop::setLogger()) to trace events like connect, frame, close.
  • Backward incompatibility: Version 2+ uses typed frames (PSR-7 style); avoid manual frame->frame() construction—always use factory methods like Websocket\text()/Websocket\binary().
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai