Protocols and message boundaries
TCP delivers a byte stream: one send does not necessarily correspond to one read. A codec identifies messages before onMessage runs.
ProtocolInterface
Section titled “ProtocolInterface”public static function input(string $buffer, ConnectionInterface $connection): int;public static function decode(string $buffer, ConnectionInterface $connection): mixed;public static function encode(mixed $data, ConnectionInterface $connection): string;input() returns 0 until it can determine a packet boundary, or the expected packet length. Transport accumulates bytes and decodes complete packets. Bound lengths before allocating large buffers; reject invalid framing instead of waiting forever.
| Codec | Message boundary |
|---|---|
| Text | Newline; trailing CR/LF is removed |
| Frame | Network-order uint32 payload length followed by payload |
| Http | HTTP headers, Content-Length/chunked and HTTP semantics |
| Websocket | Handshake and WebSocket frames |
Frame rejects declared payloads above 64 MiB; the connection’s maxPackageSize also applies. UDP preserves datagram boundaries without TCP ordering/delivery guarantees.
Custom codecs
Section titled “Custom codecs”Implement the interface and assign the class to $server->protocol. Encode an unambiguous packet and treat incomplete headers as incomplete input. Test fragmented messages and multiple messages in one buffer. Raw send bypasses encode; reserve it for already encoded wire data.