amphp/websocket-server
Async WebSocket server for PHP built on Amp’s event-driven concurrency. Handles upgrades, connections, message streaming, backpressure and graceful shutdown, making it easy to build real-time apps like chat, dashboards and live notifications.
Start by installing via Composer: composer require amphp/websocket-server. You’ll also need amphp/http-server for HTTP upgrade handling. The core concept is defining a Server class that implements Amp\WebsocketServer\WebsocketServer (or extends AbstractServer), and implementing onConnect(), onMessage(), and onClose() handlers. Your first use case will likely be a simple echo server: accept connections, echo received messages, and broadcast to all connected clients. Look at the examples/ directory in the repository for minimal working demos — especially echo-server.php — to bootstrap quickly.
onConnect, onMessage, onClose, onError) to manage client state and routing.WebSocketServerMiddleware, and route /ws paths to it while serving static files or API endpoints separately.SplObjectStorage) in your server class to track active connections. For larger apps, store session IDs or user IDs on connection and use them for targeted messaging.Amp\WebsocketServer\Message and Amp\WebsocketServer\Frame types directly in onMessage() to process text/binary payloads. For structured data, encode/decode JSON inside handlers.null), never block (e.g., no sleep() or file I/O without Amp\Promise\wait() or async wrapper). Use Amp\Loop for timers instead of pcntl_alarm or sleep.DefaultHandshake or implement Handshake to inject custom headers or validate origins — common when using WebSocket behind reverse proxies (Nginx/Apache).onFrame() until a complete message is received (e.g., using length prefixes or delimiters).Connection objects to unit test handlers — avoid integration tests requiring actual sockets unless necessary. Use Amp\PHPUnit\AsyncTestCase for test harnesses.How can I help you explore Laravel packages today?