amphp/websocket
Shared WebSocket components for AMPHP’s event-driven, fiber-based concurrency stack. Provides core abstractions used by amphp/websocket-server and amphp/websocket-client to build fast, non-blocking WebSocket clients and servers (PHP 8.1+).
Begin by installing the package via Composer (composer require amphp/websocket) and ensuring your environment supports Amp (PHP 8.1+ recommended). The first use case is typically building a minimal WebSocket server: extend Amp\Websocket\Server or use Amp\Websocket\Server::create() with a callback to handle incoming connections and messages. For clients, instantiate Amp\Websocket\Client and connect using await(). Check the official Amp documentation for foundational concepts (coroutines, event loop, Amp\Promise)—they’re essential to using this package correctly. Start with the included examples (e.g., examples/server.php, examples/client.php) to see echoing, broadcasting, and connection lifecycle handling.
SplObjectStorage or an array to track active connections per user/session, enabling targeted broadcasts. Dispatch messages using connection->send($frame).switch or map-based handler (e.g., $handlers[$message->getPayload()] = $handler) inside your connection callback for type-specific processing.Amp\Http\Server to serve your main app, then upgrade specific routes (e.g., /ws) to WebSocket via Amp\Websocket\Server by intercepting the handshake—this avoids coupling or port sprawl.send() return value (Promise) and await() only when necessary. Buffer outgoing data using Amp\Promise\timeout() or manual streamSetReadTimeout() patterns to avoid memory bloat.connection->ping()) with Amp\Loop timers to detect zombie connections; clean up stale entries in your registry.Amp\Parallel or async I/O patterns (e.g., database calls via amphp/postgres, amphp/redis).onMessage() receives Amp\Websocket\Frame. Always extract payload with $frame->getPayload() (string or binary) and handle UTF-8 validation manually.Amp\Log\BufferedLogger + Amp\Log\StandardErrorHandler to catch handshake failures or silent connection drops.Origin header and apply your own authentication (e.g., JWT in URL query) during the handshake (use Server::create()’s $options['handshake'] callback).amphp/redis for pub/sub or amphp/parallel workers for inter-connection messaging.How can I help you explore Laravel packages today?