From fa55a80b71aedeff33cfa7c25f86075b5a845fd3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muhammet=20=C5=9Eafak?= Date: Sun, 22 Nov 2026 13:52:17 +0300 Subject: [PATCH] docs: make docs/ the source of the wiki Replace the nested docs with the wiki's flat page set so the wiki can be generated from docs/ (ADR-004). Wiki page names are kept so wiki URLs do not change; internal links use the Page.md form. Document PHP 8.2+ as the minimum and point the README links at the new pages. --- README.md | 15 +- docs/API-Reference.md | 214 +++++++++++++++++++++++++++ docs/Architecture.md | 179 +++++++++++++++++++++++ docs/Client-Lifecycle.md | 133 +++++++++++++++++ docs/Connection-and-Channel.md | 151 +++++++++++++++++++ docs/Enums.md | 140 ++++++++++++++++++ docs/Event-Loop-Integration.md | 162 ++++++++++++++++++++ docs/Exceptions.md | 144 ++++++++++++++++++ docs/FAQ.md | 127 ++++++++++++++++ docs/Home.md | 70 +++++++++ docs/Installation.md | 56 +++++++ docs/Migration-Guide.md | 157 ++++++++++++++++++++ docs/Quick-Start.md | 127 ++++++++++++++++ docs/Recipe-Broadcast.md | 103 +++++++++++++ docs/Recipe-Chat-Server.md | 155 ++++++++++++++++++++ docs/Recipe-Custom-Channel.md | 155 ++++++++++++++++++++ docs/Recipe-Echo-Server.md | 136 +++++++++++++++++ docs/Recipe-SMTP-Client.md | 103 +++++++++++++ docs/Recipe-Self-Signed-TLS.md | 139 ++++++++++++++++++ docs/Recipes.md | 19 +++ docs/SSL-Context-Options.md | 124 ++++++++++++++++ docs/Server-Lifecycle.md | 148 +++++++++++++++++++ docs/Testing-Strategy.md | 260 +++++++++++++++++++++++++++++++++ docs/Transport-SSL.md | 77 ++++++++++ docs/Transport-TCP.md | 133 +++++++++++++++++ docs/Transport-TLS.md | 147 +++++++++++++++++++ docs/Transport-UDP.md | 144 ++++++++++++++++++ docs/_Footer.md | 1 + docs/_Sidebar.md | 38 +++++ docs/architecture.md | 133 ----------------- docs/client/ssl.md | 37 ----- docs/client/tcp.md | 56 ------- docs/client/tls.md | 66 --------- docs/client/udp.md | 40 ----- docs/cookbook/chat-server.md | 77 ---------- docs/cookbook/smtp-client.md | 71 --------- docs/getting-started.md | 88 ----------- docs/migration-1.x-to-2.x.md | 135 ----------------- docs/server/ssl.md | 35 ----- docs/server/tcp.md | 112 -------------- docs/server/tls.md | 78 ---------- docs/server/udp.md | 57 -------- 42 files changed, 3549 insertions(+), 993 deletions(-) create mode 100644 docs/API-Reference.md create mode 100644 docs/Architecture.md create mode 100644 docs/Client-Lifecycle.md create mode 100644 docs/Connection-and-Channel.md create mode 100644 docs/Enums.md create mode 100644 docs/Event-Loop-Integration.md create mode 100644 docs/Exceptions.md create mode 100644 docs/FAQ.md create mode 100644 docs/Home.md create mode 100644 docs/Installation.md create mode 100644 docs/Migration-Guide.md create mode 100644 docs/Quick-Start.md create mode 100644 docs/Recipe-Broadcast.md create mode 100644 docs/Recipe-Chat-Server.md create mode 100644 docs/Recipe-Custom-Channel.md create mode 100644 docs/Recipe-Echo-Server.md create mode 100644 docs/Recipe-SMTP-Client.md create mode 100644 docs/Recipe-Self-Signed-TLS.md create mode 100644 docs/Recipes.md create mode 100644 docs/SSL-Context-Options.md create mode 100644 docs/Server-Lifecycle.md create mode 100644 docs/Testing-Strategy.md create mode 100644 docs/Transport-SSL.md create mode 100644 docs/Transport-TCP.md create mode 100644 docs/Transport-TLS.md create mode 100644 docs/Transport-UDP.md create mode 100644 docs/_Footer.md create mode 100644 docs/_Sidebar.md delete mode 100644 docs/architecture.md delete mode 100644 docs/client/ssl.md delete mode 100644 docs/client/tcp.md delete mode 100644 docs/client/tls.md delete mode 100644 docs/client/udp.md delete mode 100644 docs/cookbook/chat-server.md delete mode 100644 docs/cookbook/smtp-client.md delete mode 100644 docs/getting-started.md delete mode 100644 docs/migration-1.x-to-2.x.md delete mode 100644 docs/server/ssl.md delete mode 100644 docs/server/tcp.md delete mode 100644 docs/server/tls.md delete mode 100644 docs/server/udp.md diff --git a/README.md b/README.md index 38ca5b3..b08f449 100644 --- a/README.md +++ b/README.md @@ -238,14 +238,13 @@ while ($yourEventLoop->running()) { ## Documentation -In-depth guides live under [`docs/`](./docs): - -- [Getting started](./docs/getting-started.md) -- [Architecture](./docs/architecture.md) -- Servers: [TCP](./docs/server/tcp.md) · [UDP](./docs/server/udp.md) · [TLS](./docs/server/tls.md) · [SSL](./docs/server/ssl.md) -- Clients: [TCP](./docs/client/tcp.md) · [UDP](./docs/client/udp.md) · [TLS](./docs/client/tls.md) · [SSL](./docs/client/ssl.md) -- Cookbook: [Chat server](./docs/cookbook/chat-server.md) · [SMTP client](./docs/cookbook/smtp-client.md) -- [Migrating from 1.x](./docs/migration-1.x-to-2.x.md) +In-depth guides live under [`docs/`](./docs/Home.md): + +- [Getting started](./docs/Quick-Start.md) +- [Architecture](./docs/Architecture.md) +- Servers and clients: [TCP](./docs/Transport-TCP.md) · [UDP](./docs/Transport-UDP.md) · [TLS](./docs/Transport-TLS.md) · [SSL](./docs/Transport-SSL.md) +- Cookbook: [Chat server](./docs/Recipe-Chat-Server.md) · [SMTP client](./docs/Recipe-SMTP-Client.md) +- [Migrating from 1.x](./docs/Migration-Guide.md) ## Development diff --git a/docs/API-Reference.md b/docs/API-Reference.md new file mode 100644 index 0000000..b103edb --- /dev/null +++ b/docs/API-Reference.md @@ -0,0 +1,214 @@ +# API Reference + +A single-page index of every public type. For the deeper "why", see the linked concept pages. + +## Factory + +### `InitPHP\Socket\Socket` + +```php +final class Socket +{ + public static function server( + Transport $transport, + string $host, + int $port, + ?Domain $domain = null, + ?float $timeout = null, + ): SocketServerInterface; + + public static function client( + Transport $transport, + string $host, + int $port, + ?Domain $domain = null, + ?float $timeout = null, + ): SocketClientInterface; +} +``` + +`Domain` is honoured only by TCP / UDP. `$timeout` is honoured only by TLS / SSL. + +## Server contracts + +### `InitPHP\Socket\Interfaces\SocketServerInterface` + +```php +interface SocketServerInterface +{ + public function getHost(): string; + public function getPort(): int; + public function getSocket(): mixed; // \Socket | resource | null + + /** @return array */ + public function getClients(): array; + + public function listen(): static; + public function close(): bool; + + public function live(callable $callback, float $idleSeconds = 0.05): void; + public function tick(callable $callback, float $waitSeconds = 0.0): int; + public function stop(): void; + public function isRunning(): bool; + + /** @param int|string|array|null $clients */ + public function broadcast(string $message, int|string|array|null $clients = null): bool; + public function register(int|string $id, SocketConnectionInterface $client): bool; + + public function wait(float $seconds): void; +} +``` + +### `InitPHP\Socket\Server\AbstractServer` + +Adds: + +```php +abstract class AbstractServer implements SocketServerInterface +{ + protected function addClient(SocketConnectionInterface $client): int; // returns the internal key + protected function evict(int $key): void; + protected function indexOf(SocketConnectionInterface $client): ?int; + protected static function splitSeconds(float $seconds): array; // [whole, microseconds] +} +``` + +### `InitPHP\Socket\Server\TCP` / `UDP` + +Concrete `ext-sockets`-backed servers. `TCP` additionally exposes: + +```php +public function backlog(int $backlog): self; // default 8, must be >= 1 +``` + +### `InitPHP\Socket\Server\AbstractStreamServer` + +The parent of `TLS` and `SSL`. Adds: + +```php +public function option(string $key, mixed $value): static; +public function timeout(float $seconds): static; +public function blocking(bool $mode = true): static; +public function crypto(?CryptoMethod $method): static; +``` + +`TLS` and `SSL` themselves carry no extra public surface — see [Transport TLS](Transport-TLS.md) / [Transport SSL](Transport-SSL.md). + +## Client contracts + +### `InitPHP\Socket\Interfaces\SocketClientInterface` + +```php +interface SocketClientInterface +{ + public function getHost(): string; + public function getPort(): int; + public function getSocket(): mixed; + + public function connect(): static; + public function disconnect(): bool; + + public function read(int $length = 1024): ?string; + public function write(string $data): ?int; +} +``` + +### `InitPHP\Socket\Client\TCP` + +```php +public function read(int $length = 1024, int $type = PHP_BINARY_READ): ?string; +``` + +(`$type` accepts `PHP_BINARY_READ` or `PHP_NORMAL_READ`.) + +### `InitPHP\Socket\Client\UDP` + +```php +public function read(int $length = 1024, int $flags = 0): ?string; +public function write(string $data, int $flags = 0): ?int; +``` + +(`$flags` accepts the standard `MSG_*` bitmasks.) + +### `InitPHP\Socket\Client\AbstractStreamClient` + +The parent of `Client\TLS` and `Client\SSL`. Adds: + +```php +public function option(string $key, mixed $value): static; +public function timeout(float $seconds): static; +public function blocking(bool $mode = true): static; +public function crypto(?CryptoMethod $method): static; +``` + +## Per-connection contract + +### `InitPHP\Socket\Interfaces\SocketConnectionInterface` + +```php +interface SocketConnectionInterface +{ + public function setId(int|string $id): static; + public function getId(): int|string|null; + + public function read(int $length = 1024): ?string; + public function write(string $data): ?int; + public function close(): bool; + public function isAlive(): bool; + + public function getSocket(): mixed; + public function getChannel(): ChannelInterface; +} +``` + +The only implementation in the package is `InitPHP\Socket\Server\ServerConnection`. + +## Channel contract + +### `InitPHP\Socket\Interfaces\ChannelInterface` + +```php +interface ChannelInterface +{ + public function read(int $length = 1024, ?int $flag = null): ?string; + public function write(string $data): ?int; + public function close(): bool; + public function isAlive(): bool; + public function getResource(): mixed; +} +``` + +Built-in implementations: + +| Class | Backing | Notes | +|---|---|---| +| `Channel\TcpChannel` | `ext-sockets` | Liveness via `MSG_PEEK | MSG_DONTWAIT`. | +| `Channel\UdpChannel` | `ext-sockets` (shared listening socket) | Per-peer buffer drained by `read()`. Exposes `feed()`, `getPeerHost()`, `getPeerPort()`, `peerKey()`. | +| `Channel\StreamChannel` | stream resource | Liveness via `feof()`. | + +## Enums + +See [Enums](Enums.md) for the full reference. + +```php +InitPHP\Socket\Enum\Transport // TCP, UDP, TLS, SSL +InitPHP\Socket\Enum\Domain // V4, V6, UNIX +InitPHP\Socket\Enum\CryptoMethod // SSLv2/3/23, ANY, TLS, TLSv1_0/1_1/1_2 +``` + +## Exceptions + +See [Exceptions](Exceptions.md) for the full reference. + +```php +InitPHP\Socket\Exception\SocketExceptionInterface // marker +InitPHP\Socket\Exception\SocketException // \RuntimeException +InitPHP\Socket\Exception\SocketConnectionException // \RuntimeException +InitPHP\Socket\Exception\SocketListenException // \RuntimeException +InitPHP\Socket\Exception\SocketInvalidArgumentException // \InvalidArgumentException +``` + +## See also + +- **[Architecture](Architecture.md)** — what each type does and why. +- **[Server Lifecycle](Server-Lifecycle.md)** / **[Client Lifecycle](Client-Lifecycle.md)** — when to call each method. diff --git a/docs/Architecture.md b/docs/Architecture.md new file mode 100644 index 0000000..d0431d1 --- /dev/null +++ b/docs/Architecture.md @@ -0,0 +1,179 @@ +# Architecture + +`initphp/socket` is layered so each part has one job and is replaceable in isolation. This page walks the layers top-down, then explains the design decisions behind the more interesting ones. + +## Layers at a glance + +``` +┌──────────────────────────────────────────────────────────┐ +│ Socket (factory) │ +│ Socket::server(Transport, …) / Socket::client(Transport,…) │ +└──────────────────────────────────────────────────────────┘ + │ + ┌─────────────────┴─────────────────┐ + ▼ ▼ +┌───────────────────────┐ ┌───────────────────────┐ +│ SocketServerInterface │ │ SocketClientInterface │ +│ ── AbstractServer │ │ ── AbstractClient │ +│ ├ TCP │ │ ├ TCP │ +│ ├ UDP │ │ ├ UDP │ +│ └ AbstractStream │ │ └ AbstractStream │ +│ Server │ │ Client │ +│ ├ TLS │ │ ├ TLS │ +│ └ SSL │ │ └ SSL │ +└───────────────────────┘ └───────────────────────┘ + │ │ + ▼ │ +┌───────────────────────┐ │ (clients hold the +│ ServerConnection │ ◀─────────────────┘ resource directly) +│ (per accepted client) │ +└───────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────┐ +│ ChannelInterface │ +│ ├ TcpChannel — ext-sockets, MSG_PEEK liveness │ +│ ├ UdpChannel — ext-sockets, peer buffer │ +│ └ StreamChannel — fopen / fread / feof │ +└─────────────────────────────────────────────────┘ +``` + +## The factory + +`InitPHP\Socket\Socket` is the only public entry point. It takes a `Transport` enum case and dispatches to the right concrete class: + +```php +public static function server( + Transport $transport, + string $host, + int $port, + ?Domain $domain = null, // TCP/UDP only + ?float $timeout = null, // TLS/SSL only +): SocketServerInterface; +``` + +The factory does not bind, listen or connect. It returns a configured-but-passive instance — the caller decides when to drive the lifecycle. See [Server Lifecycle](Server-Lifecycle.md) and [Client Lifecycle](Client-Lifecycle.md). + +## Servers + +Every server implements `SocketServerInterface`: + +| Method | What it does | +|---|---| +| `listen()` | Bind and start listening. Does **not** accept any client. | +| `live(cb, idle)` | Run the accept/dispatch loop until `stop()` is called. | +| `tick(cb, wait)` | One iteration of the loop. Returns event count. | +| `stop()` | Cooperatively exit `live()`. | +| `close()` | Tear down all clients + the listening socket. | +| `broadcast(msg, ids?)` | Fan out to all / by-id / by-list. | +| `register(id, conn)` | Map an addressable id to a connection. | +| `getClients()` | `array`. | +| `wait(seconds)` | Sub-second sleep helper. | + +`AbstractServer` carries the registry / broadcast / wait helpers. `Server\TCP` and `Server\UDP` plug into `ext-sockets`. `AbstractStreamServer` plugs into the stream wrapper family and is the common parent of `Server\TLS` and `Server\SSL`. + +## Clients + +Symmetric to servers, every client implements `SocketClientInterface`: + +| Method | What it does | +|---|---| +| `connect()` | Open the connection. | +| `disconnect()` | Close it. Idempotent. | +| `read(len)` | Receive up to `len` bytes. `null` on no data / failure. | +| `write(data)` | Send `data`. Returns bytes written or `null`. | + +`Client\TCP` and `Client\UDP` use `ext-sockets` directly. `AbstractStreamClient` (parent of `Client\TLS` and `Client\SSL`) wraps `stream_socket_client` and additionally exposes `option()`, `timeout()`, `blocking()` and `crypto()` chainables. + +## ServerConnection + +When a server accepts a new peer, it wraps the underlying handle in a `Channel` and the channel in a `ServerConnection`. The connection is **only** identity plus delegation: + +```php +final class ServerConnection implements SocketConnectionInterface +{ + private int|string|null $id = null; + + public function __construct(private readonly ChannelInterface $channel) {} + + public function read(int $length = 1024): ?string { return $this->channel->read($length); } + public function write(string $data): ?int { return $this->channel->write($data); } + public function close(): bool { return $this->channel->close(); } + public function isAlive(): bool { return $this->channel->isAlive(); } + public function getSocket(): mixed { return $this->channel->getResource(); } + public function getChannel(): ChannelInterface { return $this->channel; } + public function setId(int|string $id): static { /* … */ } + public function getId(): int|string|null { /* … */ } +} +``` + +This split keeps the per-connection object honest about its scope. Tests can replace the channel with a fake to exercise broadcasting / id mapping in isolation — see [Testing Strategy](Testing-Strategy.md). + +## Channels (Strategy) + +The 1.x release had a `switch ($transportType)` ladder inside `ServerClient::push()`, `read()`, `close()` and `isDisconnected()`. The 2.x split moves the transport-specific I/O into dedicated channels: + +- **`TcpChannel`** uses `socket_recv` / `socket_write` and detects peer close non-destructively with `MSG_PEEK | MSG_DONTWAIT`. +- **`StreamChannel`** uses `fread` / `fwrite` and asks `feof()` whether the peer is gone — without consuming bytes. +- **`UdpChannel`** binds an identity (`peerHost:peerPort`) to the server's listening socket. The server routes inbound datagrams into the channel's local buffer via `feed()`; reads drain the buffer. Writes use `socket_sendto` directly. + +Adding a new transport is "implement `ChannelInterface`", not "edit every `switch` in the package". + +## The server loop + +The accept/dispatch flow has two layers — `live()` is the long-running while loop, `tick()` is a single iteration: + +```php +// AbstractServer::live (simplified) +public function live(callable $callback, float $idleSeconds = 0.05): void +{ + $this->running = true; + while ($this->isRunning()) { + $this->tick($callback, $idleSeconds); + } +} +``` + +`tick()` is implemented per-server. It always follows the same shape: + +1. Build the read set: `[listenSocket, ...activeClientSockets]`. +2. Hand it to `socket_select` / `stream_select` with the caller-supplied timeout. +3. For every resource the kernel reports readable: + - If it is the listening socket → `accept()` a new client and wrap it in a channel. + - If it is an existing client → check liveness, then invoke the callback. + +UDP departs slightly: it has no `accept()`, so the loop is `recvfrom` → lookup-or-create the `UdpChannel` for that peer → feed the buffer → invoke the callback. + +## Why `select()`-driven? + +The 1.x `live()` called blocking `socket_accept()` on every iteration, so existing clients were ignored until a new one connected. The 2.x loop tells the kernel about every resource it cares about and then services only the ones that are actually ready. This makes the server responsive to data on existing connections while still accepting new ones. + +## Liveness, no data loss + +`isAlive()` never touches the application payload: + +- **TCP** — `socket_recv($sock, $buf, 1, MSG_PEEK | MSG_DONTWAIT)`. A 0 result means peer closed; `EAGAIN` / `EWOULDBLOCK` means alive-but-quiet. +- **Stream (TLS / SSL)** — `feof()` after a `is_resource()` guard. +- **UDP** — an in-process `alive` flag; UDP has no connection state, so dead peers are detected by application-level TTL. + +This was the worst 1.x bug: `isDisconnected()` read a line off the socket every iteration and **discarded it**, so the application callback never saw the payload it expected. 2.x's `isAlive()` is non-destructive by contract. + +## Exceptions + +Every exception in the package implements `SocketExceptionInterface`, so a single catch covers them all: + +``` +SocketExceptionInterface (marker) +├─ SocketException (extends \RuntimeException) +│ ├─ SocketConnectionException +│ └─ SocketListenException +└─ SocketInvalidArgumentException (extends \InvalidArgumentException) +``` + +See [Exceptions](Exceptions.md) for the full reference. + +## Where to next + +- **[Server Lifecycle](Server-Lifecycle.md)** — the public method contract per state. +- **[Connection and Channel](Connection-and-Channel.md)** — the per-accepted-client object and its strategy. +- **[Event Loop Integration](Event-Loop-Integration.md)** — how to plug `tick()` into an external loop. diff --git a/docs/Client-Lifecycle.md b/docs/Client-Lifecycle.md new file mode 100644 index 0000000..9384b49 --- /dev/null +++ b/docs/Client-Lifecycle.md @@ -0,0 +1,133 @@ +# Client Lifecycle + +A client has three states. The transitions are short — clients are simpler than servers because they own a single peer. + +``` +constructed ──connect()──► connected ──disconnect()──► closed +``` + +## 1. Construct + +```php +use InitPHP\Socket\Socket; +use InitPHP\Socket\Enum\{Transport, Domain}; + +$client = Socket::client(Transport::TCP, '127.0.0.1', 9000, Domain::V4); +``` + +What happens: + +- Host and port are validated synchronously. Empty host or out-of-range port throws `SocketInvalidArgumentException`. +- For TLS / SSL, the optional `$timeout` is stored and used by `connect()`. +- No network call has been made yet. + +## 2. Connect + +```php +$client->connect(); +``` + +- **TCP / UDP** — `socket_create` then `socket_connect`. UDP "connect" just locks the peer locally; there is no datagram round-trip. +- **TLS / SSL** — `stream_socket_client` with an SSL context built from `option()` calls. The TLS handshake completes inside this call. + +If anything goes wrong (the peer is not listening, the certificate fails verification, the handshake times out), `connect()` throws `SocketConnectionException`. The message contains PHP's underlying errno and description. + +```php +try { + $client->connect(); +} catch (\InitPHP\Socket\Exception\SocketConnectionException $e) { + // retry, fall back, log, … +} +``` + +Calling `connect()` a second time **throws** `SocketException` — clients are single-use, not reusable. Construct a fresh instance to retry. + +## 3. Read and write + +```php +$bytes = $client->write("PING\r\n"); // returns int bytes written, or null on failure +$reply = $client->read(1024); // returns ?string, null = no data / failure +``` + +Both `read()` and `write()` return `null` on failure rather than raising. This makes happy-path code uncluttered while still leaving room for error handling: + +```php +$reply = $client->read(1024); +if ($reply === null) { + // EOF, error, or non-blocking read with nothing yet +} +``` + +### Transport-specific extras + +- **TCP** — `read(int $length = 1024, int $type = PHP_BINARY_READ)`. Pass `PHP_NORMAL_READ` to read line-by-line. +- **UDP** — `read(int $length = 1024, int $flags = 0)` and `write(string $data, int $flags = 0)` accept the standard `MSG_*` flags. +- **TLS / SSL** — `option()`, `timeout()`, `blocking()` and `crypto()` chainables on top of the base API. + +## 4. Disconnect + +```php +$client->disconnect(); +``` + +- TCP / UDP — `socket_close`. +- TLS / SSL — `fclose` on the stream. + +`disconnect()` is **idempotent** — call it multiple times, call it before `connect()`, both are fine and return `true`. + +After `disconnect()`: + +- `getSocket()` returns `null`. +- `read()` / `write()` return `null`. +- `connect()` is not allowed again (it would refuse on the "already connected" check earlier in the lifecycle of a fresh instance; here the contract is "this instance is done"). + +## TLS / SSL configuration + +The TLS / SSL clients add fluent setters that mirror the SSL stream context (see [SSL Context Options](SSL-Context-Options.md)): + +```php +$client = Socket::client(Transport::TLS, 'example.com', 443, timeout: 5.0) + ->option('verify_peer', true) + ->option('verify_peer_name', true) + ->option('cafile', '/etc/ssl/certs/ca-certificates.crt') + ->option('SNI_enabled', true) + ->timeout(2.0) + ->blocking(true); + +$client->connect(); +``` + +`crypto()` can be used **after** `connect()` to enable / disable encryption on the fly — useful for protocols that start unencrypted and `STARTTLS` later: + +```php +use InitPHP\Socket\Enum\CryptoMethod; + +$client = Socket::client(Transport::TLS, 'mail.example.com', 587); +$client->connect(); +// EHLO, STARTTLS, … +$client->crypto(CryptoMethod::TLSv1_2); // upgrade +``` + +Calling `crypto()` **before** `connect()` throws `SocketException` (there is no stream to toggle yet). + +## Method matrix + +| Method | Before `connect()` | After `connect()` | After `disconnect()` | +|---|---|---|---| +| `connect()` | opens the connection | **throws** | **throws** | +| `disconnect()` | no-op (returns `true`) | closes | no-op | +| `read()` | returns `null` | reads | returns `null` | +| `write()` | returns `null` | writes | returns `null` | +| `getSocket()` | `null` | live handle | `null` | +| `getHost()` / `getPort()` | configured | configured | configured | +| `option()` (TLS / SSL) | stores in context | stores in context | stores in context | +| `timeout()` (TLS / SSL) | stores | stores **and** applies to live stream | stores | +| `blocking()` (TLS / SSL) | stores | stores **and** applies to live stream | stores | +| `crypto()` (TLS / SSL) | **throws** | toggles | depends — usually unsafe | + +## See also + +- **[Server Lifecycle](Server-Lifecycle.md)** — symmetric story for the accept side. +- **[Transport TCP](Transport-TCP.md)** / **[Transport UDP](Transport-UDP.md)** — flag arguments on `read()` / `write()`. +- **[Transport TLS](Transport-TLS.md)** — TLS handshake specifics. +- **[SSL Context Options](SSL-Context-Options.md)** — every key `option()` accepts. diff --git a/docs/Connection-and-Channel.md b/docs/Connection-and-Channel.md new file mode 100644 index 0000000..27edfd3 --- /dev/null +++ b/docs/Connection-and-Channel.md @@ -0,0 +1,151 @@ +# Connection and Channel + +When a server accepts a new peer, it wraps the underlying handle in a `Channel` (transport strategy) and the channel in a `ServerConnection` (identity + delegation). This page documents both. + +## `SocketConnectionInterface` + +What every accepted-peer object exposes to the user callback: + +```php +namespace InitPHP\Socket\Interfaces; + +interface SocketConnectionInterface +{ + public function setId(int|string $id): static; + public function getId(): int|string|null; + + public function read(int $length = 1024): ?string; + public function write(string $data): ?int; + public function close(): bool; + public function isAlive(): bool; + + public function getSocket(): mixed; + public function getChannel(): ChannelInterface; +} +``` + +### Identity + +`setId()` and `getId()` exist for one purpose — addressable broadcasts. Until the application sets an id, `getId()` returns `null`: + +```php +$server->live(function ($srv, $conn) { + $line = trim((string) $conn->read()); + if (preg_match('/^REGISTER (\w+)$/', $line, $m)) { + $srv->register($m[1], $conn); // calls $conn->setId($m[1]) internally + } +}); + +// Later, broadcast to one id: +$server->broadcast('hello admin', 'admin'); +``` + +The id can be either `int` or `string`. It is **not** unique by design — register the same id on two connections and broadcast reaches both, in registration order. + +### Reading and writing + +`read()` is non-destructive in failure modes — it returns `null` for "no data right now / EOF / underlying error", never raises. `write()` returns the number of bytes actually written, or `null` on failure. + +> Both methods delegate to the channel. The connection adds no buffering of its own; whatever the channel returns is what you get. + +### Liveness + +`isAlive()` **never consumes data**. The 1.x package's `isDisconnected()` did, and that hid every callback's payload in a 1-byte read on every loop iteration. The 2.x contract: `isAlive()` only peeks / inspects state. + +The server's accept/dispatch loop calls `isAlive()` after every `select()` returns the connection as readable. If the answer is `false`, the connection is closed and evicted before your callback runs. + +### Native handle + +`getSocket()` returns whatever the underlying transport uses: + +| Transport | Returns | +|---|---| +| TCP | `\Socket` (PHP 8 ext-sockets object) | +| UDP | `\Socket` (the server's listening socket, shared by every UdpChannel) | +| TLS / SSL | `resource` (a stream) | + +For long-lived custom logic, prefer `getChannel()` — it gives you the strategy object directly and is typed. + +## `ChannelInterface` + +The transport strategy that does the actual I/O: + +```php +namespace InitPHP\Socket\Interfaces; + +interface ChannelInterface +{ + public function read(int $length = 1024, ?int $flag = null): ?string; + public function write(string $data): ?int; + public function close(): bool; + public function isAlive(): bool; + public function getResource(): mixed; +} +``` + +`ChannelInterface` is the seam if you ever need to add a new transport — see [Recipe Custom Channel](Recipe-Custom-Channel.md) for a worked example. + +## The three built-in channels + +### `Channel\TcpChannel` + +Backed by `ext-sockets`: + +- `read()` calls `socket_read` with `PHP_BINARY_READ` by default; pass `PHP_NORMAL_READ` to read line-by-line. +- `write()` calls `socket_write`. +- `isAlive()` uses `socket_recv($s, $tmp, 1, MSG_PEEK | MSG_DONTWAIT)`. A 0 result is "peer closed"; `EAGAIN` / `EWOULDBLOCK` is "no data right now, still alive". +- `close()` calls `socket_close` and is idempotent. + +### `Channel\StreamChannel` + +Backed by stream resources (TLS / SSL servers): + +- `read()` calls `fread`; refuses lengths < 1 by returning `null`. +- `write()` calls `fwrite`. +- `isAlive()` is `is_resource() && !feof()`. +- `close()` calls `fclose` and is idempotent. + +### `Channel\UdpChannel` + +The most unusual of the three because UDP has no per-peer socket. A `UdpChannel`: + +- Holds the **server's listening socket** (shared by every channel) plus an immutable `(peerHost, peerPort)` identity. +- Carries an internal `string $buffer`. The server calls `feed(string $data)` to push inbound datagrams into the right channel. +- `read()` drains the buffer up to `$length` bytes. There is no kernel-level read here — the server already did the `recvfrom`. +- `write()` calls `socket_sendto` on the listening socket with the bound peer. +- `close()` flips an internal alive flag and clears the buffer. It does **not** close the listening socket — that belongs to the server. + +Extra methods on `UdpChannel`: + +```php +$channel->feed(string $data): void; // server-side: push inbound bytes +$channel->getPeerHost(): string; +$channel->getPeerPort(): int; +$channel->peerKey(): string; // 'host:port' — used as the server's map key +``` + +The server keeps a `peerKey() → internalKey` index so returning peers reuse their existing channel rather than spawning a new one per packet. + +## Building a connection by hand + +You normally never construct a `ServerConnection` yourself — the server does it after each `accept` / `recvfrom`. But the constructor is public and trivially mockable, which is what makes the broadcast / registry logic so easy to unit-test: + +```php +use InitPHP\Socket\Server\ServerConnection; +use InitPHP\Socket\Channel\StreamChannel; + +$stream = fopen('php://memory', 'r+'); +$conn = new ServerConnection(new StreamChannel($stream)); +$conn->setId('admin'); +$conn->write("hello\n"); +rewind($stream); +echo fread($stream, 1024); // hello\n +``` + +This pattern is exactly how the package's own [Testing Strategy](Testing-Strategy.md) exercises the abstract server logic without binding any real ports. + +## See also + +- **[Architecture](Architecture.md)** — where connections and channels sit in the layered model. +- **[Recipe Custom Channel](Recipe-Custom-Channel.md)** — implementing `ChannelInterface` from scratch. +- **[Testing Strategy](Testing-Strategy.md)** — using fake channels in tests. diff --git a/docs/Enums.md b/docs/Enums.md new file mode 100644 index 0000000..5460e92 --- /dev/null +++ b/docs/Enums.md @@ -0,0 +1,140 @@ +# Enums + +The package replaces every magic integer / string flag with a PHP enum. Three enums live under `InitPHP\Socket\Enum`. + +## `Transport` + +Selects the transport for `Socket::server()` / `Socket::client()`. + +```php +namespace InitPHP\Socket\Enum; + +enum Transport: string +{ + case TCP = 'tcp'; + case UDP = 'udp'; + case TLS = 'tls'; + case SSL = 'ssl'; + + public function isStream(): bool; // TLS or SSL + public function isDatagram(): bool; // UDP + public function scheme(): string; // value alias for stream URLs +} +``` + +### Predicates + +```php +Transport::TLS->isStream(); // true +Transport::SSL->isStream(); // true +Transport::TCP->isStream(); // false + +Transport::UDP->isDatagram(); // true +Transport::TCP->isDatagram(); // false + +Transport::TLS->scheme(); // 'tls' (used as 'tls://host:port') +``` + +### Picking a case + +| Use case | Case | +|---|---| +| Plain TCP server / client | `Transport::TCP` | +| Datagrams | `Transport::UDP` | +| Modern TLS-encrypted streams | `Transport::TLS` | +| Legacy implicit-TLS on `ssl://` (SMTPS 465, IMAPS 993, …) | `Transport::SSL` | + +## `Domain` + +The address family for TCP / UDP. Ignored for TLS / SSL (the stream wrapper figures it out from the URL). + +```php +namespace InitPHP\Socket\Enum; + +enum Domain: string +{ + case V4 = 'v4'; + case V6 = 'v6'; + case UNIX = 'unix'; + + public function toAddressFamily(): int; + public static function fromName(?string $name): self; +} +``` + +| Case | `toAddressFamily()` | +|---|---| +| `Domain::V4` | `AF_INET` | +| `Domain::V6` | `AF_INET6` | +| `Domain::UNIX` | `AF_UNIX` | + +`fromName()` is a convenience for parsing from configuration: + +```php +Domain::fromName(null); // Domain::V4 (null and '' default to V4) +Domain::fromName(''); // Domain::V4 +Domain::fromName('v6'); // Domain::V6 +Domain::fromName('V6'); // Domain::V6 (case-insensitive) +Domain::fromName('unix'); // Domain::UNIX +Domain::fromName('ipx'); // SocketInvalidArgumentException +``` + +## `CryptoMethod` + +A pinned TLS / SSL protocol version. Maps to PHP's `STREAM_CRYPTO_METHOD_*_CLIENT` and `STREAM_CRYPTO_METHOD_*_SERVER` constants. + +```php +namespace InitPHP\Socket\Enum; + +enum CryptoMethod: string +{ + case SSLv2 = 'sslv2'; + case SSLv3 = 'sslv3'; + case SSLv23 = 'sslv23'; + case ANY = 'any'; + case TLS = 'tls'; + case TLSv1_0 = 'tlsv1.0'; + case TLSv1_1 = 'tlsv1.1'; + case TLSv1_2 = 'tlsv1.2'; + + public function forClient(): int; + public function forServer(): int; + public static function fromName(string $name): self; +} +``` + +### Picking the right method + +Prefer the highest version your peers support. **`CryptoMethod::TLSv1_2`** is the safe modern default; only fall back to lower versions if you have a specific legacy peer. + +```php +$client->crypto(CryptoMethod::TLSv1_2); +$server->crypto(CryptoMethod::TLSv1_2); +``` + +### `fromName()` + +Convenience for parsing from configuration. Case-insensitive: + +```php +CryptoMethod::fromName('TLSv1.2'); // CryptoMethod::TLSv1_2 +CryptoMethod::fromName('tlsv1.2'); // CryptoMethod::TLSv1_2 +CryptoMethod::fromName('tlsv9'); // SocketInvalidArgumentException +``` + +### Server vs client constants + +PHP exposes separate constants for the server and client ends: + +```php +CryptoMethod::TLSv1_2->forClient(); // STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT +CryptoMethod::TLSv1_2->forServer(); // STREAM_CRYPTO_METHOD_TLSv1_2_SERVER +``` + +The `AbstractStreamServer::crypto()` and `AbstractStreamClient::crypto()` setters pick the right side automatically — you only ever pass the enum case. + +## See also + +- **[Transport TLS](Transport-TLS.md)** — when to call `crypto()`. +- **[SSL Context Options](SSL-Context-Options.md)** — the `option()` keys that work with these enums. +- **[API Reference](API-Reference.md)** — full surface in one page. diff --git a/docs/Event-Loop-Integration.md b/docs/Event-Loop-Integration.md new file mode 100644 index 0000000..5c624d9 --- /dev/null +++ b/docs/Event-Loop-Integration.md @@ -0,0 +1,162 @@ +# Event Loop Integration + +`live()` is convenient but greedy — it never yields control. If you already run an event loop (ReactPHP, Amp, Symfony's Console Application, an HTTP server, a queue worker), drive the server from your own loop via `tick()`. + +## The `tick()` contract + +```php +public function tick(callable $callback, float $waitSeconds = 0.0): int; +``` + +- Performs **exactly one** `socket_select` / `stream_select` call with `$waitSeconds` as the timeout. +- Accepts at most one pending connection and services every readable existing client. +- Returns the number of events handled (`0` if `select()` timed out with no readiness). +- Throws `SocketException` if called before `listen()`. + +`live()` is implemented as + +```php +public function live(callable $callback, float $idleSeconds = 0.05): void +{ + $this->running = true; + while ($this->isRunning()) { + $this->tick($callback, $idleSeconds); + } +} +``` + +so there is nothing magical about it — you can always re-implement it. + +## Three integration patterns + +### 1. Polling inside a host loop + +Your scheduler decides when to yield; the server gets a tiny slice each tick: + +```php +$server->listen(); + +while ($host->isRunning()) { + $events = $server->tick( + fn ($srv, $conn) => $myHandler($srv, $conn), + waitSeconds: 0.0, // non-blocking; return immediately if no readiness + ); + if ($events === 0) { + $host->yield(); + } +} + +$server->close(); +``` + +Use `waitSeconds: 0.0` when the host loop has its own idle strategy. The socket layer never blocks; it just reports whether work was found. + +### 2. Time-budgeted batches + +Give the server a fixed slice of wall-clock time per host tick: + +```php +$server->listen(); + +while ($host->isRunning()) { + $deadline = microtime(true) + 0.01; // 10 ms budget per host tick + do { + $events = $server->tick(callback, waitSeconds: 0.0); + } while ($events > 0 && microtime(true) < $deadline); + + $host->yield(); +} +``` + +Useful inside a single-process app where you want bounded socket latency without the socket layer monopolising the CPU. + +### 3. Blocking select with an external wake-up + +If the host has nothing else to do (a pure socket worker), let `tick()` block on `select()` and signal it externally to wake up: + +```php +$server->listen(); + +pcntl_signal(SIGTERM, fn () => $server->stop()); +pcntl_signal(SIGINT, fn () => $server->stop()); + +while ($server->isRunning()) { + $server->tick(callback, waitSeconds: 1.0); + pcntl_signal_dispatch(); +} + +$server->close(); +``` + +`tick()` returns once a second even when idle, giving the signal dispatcher a chance to flip `$running` to `false`. + +> Without `pcntl_async_signals(true)`, signals are only processed at `pcntl_signal_dispatch()`. Inside a busy `select()` they queue up and fire on the next `tick()` return. + +## Calling `tick()` from the callback + +The callback may call `tick()` reentrantly — but each call re-enters `select()`, which is rarely what you want. The conventional pattern is to set state from the callback and let the outer loop pick it up: + +```php +$server->live(function ($srv, $conn) { + if ($conn->read() === 'shutdown') { + $srv->stop(); // outer live() will exit on the next iteration + } +}); +``` + +`stop()` is the safe way to break out of `live()` mid-callback. + +## Mixing servers in one loop + +There is no shared scheduler — each server keeps its own `select()` call. Drive them sequentially in the host loop: + +```php +$tcp = Socket::server(Transport::TCP, '0.0.0.0', 8080); +$udp = Socket::server(Transport::UDP, '0.0.0.0', 8081); +$tcp->listen(); +$udp->listen(); + +while ($host->running) { + $tcp->tick($onTcp, waitSeconds: 0.0); + $udp->tick($onUdp, waitSeconds: 0.0); + if (! $host->hasOtherWork()) { + usleep(1_000); + } +} + +$tcp->close(); +$udp->close(); +``` + +If you have many servers and want them in the same `select()`, the cleanest path is a custom outer loop that pulls the underlying handles from `getSocket()` and runs a single `socket_select` / `stream_select` itself, then dispatches via per-server `tick(waitSeconds: 0.0)` calls. The package does not ship a multiplexer — see [Recipe Custom Channel](Recipe-Custom-Channel.md) for the shape such an extension takes. + +## Testing with `tick()` + +`tick()` is the seam that makes deterministic integration tests easy: + +```php +$server = new TcpServer('127.0.0.1', $port); +$server->listen(); + +$client = new TcpClient('127.0.0.1', $port); +$client->connect(); + +$server->tick(fn () => null, 0.2); // accept the queued client +self::assertCount(1, $server->getClients()); + +$client->write('ping'); + +$received = null; +$server->tick(function ($srv, $conn) use (&$received) { + $received = $conn->read(1024); +}, 0.2); + +self::assertSame('ping', $received); +``` + +No `pcntl_fork`, no threads, no flakiness. See [Testing Strategy](Testing-Strategy.md) for the full set of patterns the package's own test suite uses. + +## See also + +- **[Server Lifecycle](Server-Lifecycle.md)** — what state `listen` / `stop` / `close` actually mutate. +- **[Testing Strategy](Testing-Strategy.md)** — the package's own use of `tick()` in tests. diff --git a/docs/Exceptions.md b/docs/Exceptions.md new file mode 100644 index 0000000..0455bbd --- /dev/null +++ b/docs/Exceptions.md @@ -0,0 +1,144 @@ +# Exceptions + +The 2.x release introduced a marker interface so a single `catch` covers every failure mode in the package. + +## Hierarchy + +``` +SocketExceptionInterface (marker — extends \Throwable) +├─ SocketException (extends \RuntimeException) +│ ├─ SocketConnectionException +│ └─ SocketListenException +└─ SocketInvalidArgumentException (extends \InvalidArgumentException) +``` + +All four concrete classes live under `InitPHP\Socket\Exception`. + +## `SocketExceptionInterface` + +A marker — no methods of its own. Catch it to handle every socket failure in one place: + +```php +use InitPHP\Socket\Exception\SocketExceptionInterface; + +try { + $server->listen(); + $client->connect(); +} catch (SocketExceptionInterface $e) { + // bind failed, connect refused, invalid argument — anything from the package + $logger->error('socket boom', ['err' => $e->getMessage()]); +} +``` + +Because the interface extends `\Throwable`, IDEs and static analysers understand it as a real exception type. + +## `SocketException` + +The runtime base. Thrown when something failed at the network layer that is not an explicit "could not connect" / "could not listen" / "invalid argument". Extends `\RuntimeException`. + +Common situations: + +- `socket_create` returned `false`. +- `socket_bind` failed (port in use, permission denied, address not available). +- `socket_select` / `stream_select` reported an error other than `EINTR`. +- `listen()` called twice. +- `connect()` called twice on a client. +- `tick()` called before `listen()`. +- `crypto()` called before `connect()` on a TLS / SSL client. + +```php +try { + $server->listen(); + $server->listen(); // second call +} catch (\InitPHP\Socket\Exception\SocketException $e) { + // "Server is already listening." +} +``` + +## `SocketConnectionException` + +Subclass of `SocketException`. Thrown when an outbound connection fails: + +- TCP `socket_connect` refused (no listener, network unreachable, …). +- UDP `socket_connect` refused (rare — usually an `EACCES`-class error). +- TLS / SSL `stream_socket_client` failed (handshake error, certificate verification, timeout). +- Server-side `socket_accept` errored (non-`EINTR`). + +```php +try { + $client->connect(); +} catch (\InitPHP\Socket\Exception\SocketConnectionException $e) { + // "Socket Connection Error : Connection refused" +} +``` + +The exception message includes PHP's underlying error string. + +## `SocketListenException` + +Subclass of `SocketException`. Specific to bind / listen failures on the server side: + +- `socket_listen` failed. +- `stream_socket_server` failed (TLS / SSL bind). + +```php +try { + $server->listen(); +} catch (\InitPHP\Socket\Exception\SocketListenException $e) { + // "stream_socket_server failed (98): Address already in use" +} +``` + +The split between `SocketException` (bind failure) and `SocketListenException` (listen failure) mirrors PHP's two-step API. In practice most callers catch the more general `SocketException`. + +## `SocketInvalidArgumentException` + +Extends `\InvalidArgumentException` **and** implements `SocketExceptionInterface`. Thrown synchronously by constructors and configuration setters when the input is wrong: + +- Empty host. +- Port outside `1‒65535`. +- `Domain::fromName('ipx')` — unknown domain string. +- `CryptoMethod::fromName('tlsv9')` — unknown crypto method. +- `TCP\backlog(-1)` — non-positive backlog. +- `StreamChannel::__construct($notAResource)` — handed a non-resource. + +Catch either the native parent or the marker interface, depending on whether you want package-only granularity: + +```php +try { + Socket::server(Transport::TCP, '', 80); +} catch (\InvalidArgumentException $e) { // generic + // ... +} catch (SocketExceptionInterface $e) { // package-only + // ... +} +``` + +## Error-message conventions + +Every package message starts with the PHP-level call that failed when possible, so the cause is searchable: + +``` +"socket_bind failed: Address already in use" +"stream_socket_client failed (61): Connection refused" +"Server is already listening." +"backlog must be at least 1." +``` + +If a system call returned a numeric errno, the format is `(errno) description`. For PHP-level guards the message is a plain English sentence. + +## Catching strategy + +| Goal | Catch | +|---|---| +| Anything from the package | `SocketExceptionInterface` | +| Runtime failures only (bind / listen / connect / select) | `SocketException` | +| "Could not connect to peer" | `SocketConnectionException` | +| "Could not bind / listen on port" | `SocketListenException` | +| "Caller passed something invalid" | `SocketInvalidArgumentException` (or generic `\InvalidArgumentException`) | + +## See also + +- **[Server Lifecycle](Server-Lifecycle.md)** — which methods throw which exception. +- **[Client Lifecycle](Client-Lifecycle.md)** — symmetric story for clients. +- **[FAQ](FAQ.md)** — common error messages and what they mean. diff --git a/docs/FAQ.md b/docs/FAQ.md new file mode 100644 index 0000000..371e0ab --- /dev/null +++ b/docs/FAQ.md @@ -0,0 +1,127 @@ +# FAQ + +A grab-bag of questions that come up often. If something here doesn't match what you see, [open an issue](https://github.com/InitPHP/Socket/issues) — both the docs and the package improve from real reports. + +## Is this a framework? An async runtime? + +Neither. `initphp/socket` is a thin, transport-agnostic façade over `ext-sockets` and the stream socket family. It runs a non-blocking `select`-driven loop inside your normal PHP process. There is no fiber scheduler, no promise framework, no daemonisation — those layers are someone else's job (or yours). + +## Can I run multiple servers in the same process? + +Yes — but the package does not multiplex them for you. Each server has its own `tick()` / `live()` loop. Wire them together in your own scheduler: + +```php +$tcp->listen(); +$udp->listen(); +while ($running) { + $tcp->tick($onTcp, waitSeconds: 0.0); + $udp->tick($onUdp, waitSeconds: 0.0); + usleep(1_000); +} +``` + +See [Event Loop Integration](Event-Loop-Integration.md) for patterns. + +## Why does `tick()` exist on top of `live()`? + +`live()` is "easy mode" — start it and don't worry about anything else. `tick()` is "embedding mode" — let your existing event loop decide when the socket layer gets CPU. They share the same loop body; `live()` just calls `tick()` until something flips `$running` to false. + +Tests use `tick()` because it gives deterministic single-step control. + +## How do I gracefully shut down a `live()` loop? + +Call `$server->stop()` from inside the callback, or from a signal handler: + +```php +pcntl_signal(SIGTERM, fn () => $server->stop()); +pcntl_signal(SIGINT, fn () => $server->stop()); +pcntl_async_signals(true); + +$server->live(...); +$server->close(); +``` + +`stop()` only flips the flag; you still call `close()` afterwards to tear down sockets. + +## Why does my server only accept one client? + +You almost certainly hit the 1.x bug. 2.x's `live()` accepts many clients in a non-blocking loop. If you upgraded, double-check you replaced `connection()` with `listen()` and that you're not calling `socket_accept` yourself — see the [Migration Guide](Migration-Guide.md). + +If you're already on 2.x and seeing one-accept-only behaviour, please [file an issue](https://github.com/InitPHP/Socket/issues). + +## Why does `$conn->read()` return `null`? + +Three possibilities: + +1. Nothing to read right now (the socket is non-blocking and the kernel has no bytes for you). +2. The peer closed the connection (EOF). +3. An underlying error. + +The package returns `null` for all three because most callers want a single "no data" branch. If you need to distinguish them, inspect `$conn->isAlive()` and `socket_last_error()` / `socket_strerror()`. + +## Why does my callback receive an empty string? + +It does **not**, by contract: `read()` returns `?string` and `null` covers both "no data" and "empty string", so the callback never sees an empty string from `$conn->read()`. If you see `""` somewhere, the source is your own code or a wrapper around the connection. (Channels are also expected to honour this contract.) + +## Why does `live()` use CPU when nothing is happening? + +It calls `socket_select` with `idleSeconds` as the timeout. The default is 50 ms — so the loop wakes up 20 times a second even when idle. If that is too aggressive, raise `idleSeconds`: + +```php +$server->live($callback, idleSeconds: 1.0); // wake once a second when idle +``` + +Trade-off: a higher idle means new accept events are detected later (latency-bound by the timeout). For most chat-style servers, `0.05` is fine. For mostly-idle services, `1.0` is fine too. + +## What about Windows? + +The package itself runs on Windows (the `ext-sockets` and stream wrappers exist there). The **TLS integration test** uses `pcntl_fork` and is automatically skipped on Windows. The actual TLS server / client classes work the same on every OS. + +## What about backpressure on `write()`? + +`write()` returns the number of bytes the OS actually accepted. A "short write" — `strlen($data) > $written` — means the OS buffer is partly full. The package does **not** loop or queue the unsent bytes for you; you decide whether to retry or back off. In 99% of LAN / loopback scenarios, single-shot writes work, but plan for short writes in real-world deployments. + +## How do I detect peer disconnect without reading? + +`$conn->isAlive()`. For TCP it uses `MSG_PEEK | MSG_DONTWAIT`, for streams it uses `feof()`. Both are non-destructive. The `live()` / `tick()` loop already calls `isAlive()` between accept and dispatch, so a closed peer is evicted before your callback runs. + +## Why is my TLS handshake timing out? + +Three common reasons: + +1. **The listening stream was set non-blocking** (1.x style). In 2.x the package keeps the listen socket blocking specifically so `stream_socket_accept` has time to finish the handshake. +2. **The `timeout` constructor argument is too small.** The handshake takes one to a few hundred milliseconds; budget at least 1.0 second. +3. **A certificate / hostname mismatch.** Set `verify_peer = false` temporarily to confirm; if it works, fix the trust configuration. See [SSL Context Options](SSL-Context-Options.md). + +## Why does my UDP server keep clients that never spoke again? + +UDP has no kernel-level disconnect signal. The package keeps the channel until you `close()` it explicitly. Track `lastSeen` per peer and evict on TTL — example in [Transport UDP](Transport-UDP.md). + +## Can I use this with ReactPHP / Amp / Swoole? + +Yes — drive `tick()` from their loop. `tick($cb, waitSeconds: 0.0)` is non-blocking and returns immediately; you yield back to the host loop and pick up next iteration. The package does not integrate with any of these natively, but the seam is intentional. See [Event Loop Integration](Event-Loop-Integration.md). + +## How do I add a new transport (e.g. WebSocket)? + +Implement `ChannelInterface` for the I/O and (optionally) extend `AbstractServer` for the accept logic. The factory is closed for extension by design — call your concrete server directly. See [Recipe Custom Channel](Recipe-Custom-Channel.md). + +## How is the test suite so fast? + +Most of it is unit tests over fakes (no I/O). The integration tests run on loopback with `tick()` to avoid sleeping. The TLS test is the only one that forks, and it forks only the client side. Full suite: **96 tests in under a second**. + +## Where do I report a bug? + +[InitPHP/Socket/issues](https://github.com/InitPHP/Socket/issues). Include: + +- Package version (`composer show initphp/socket`). +- PHP version and OS. +- A minimal reproducer (≤ 30 lines). +- Expected vs actual output. + +A failing test or a `nc` transcript helps a lot. + +## See also + +- **[Migration Guide](Migration-Guide.md)** — moving from 1.x. +- **[Architecture](Architecture.md)** — the underlying model. +- **[Testing Strategy](Testing-Strategy.md)** — write deterministic tests for your own server code. diff --git a/docs/Home.md b/docs/Home.md new file mode 100644 index 0000000..9170950 --- /dev/null +++ b/docs/Home.md @@ -0,0 +1,70 @@ +# InitPHP Socket — Documentation + +Welcome to the official documentation for **`initphp/socket`** — a lightweight TCP, UDP, TLS and SSL socket server / client toolkit for PHP 8.2+. + +```bash +composer require initphp/socket +``` + +```php +use InitPHP\Socket\Socket; +use InitPHP\Socket\Enum\Transport; + +$server = Socket::server(Transport::TCP, '127.0.0.1', 8080); +$server->listen(); +$server->live(function ($srv, $conn) { + $payload = $conn->read(1024); + if ($payload !== null) { + $conn->write("echo: {$payload}"); + } +}); +``` + +The package gives you four building blocks every long-running PHP service ends up writing by hand: + +| Layer | Class / Concept | Purpose | +|---|---|---| +| **Factory** | `Socket::server()` / `Socket::client()` | One entry point dispatching by `Transport` enum | +| **Servers** | `Server\{TCP, UDP, TLS, SSL}` | Bind, listen and dispatch with a `select`-driven loop | +| **Clients** | `Client\{TCP, UDP, TLS, SSL}` | Connect-read-write to a remote endpoint | +| **Channels** | `Channel\{Tcp, Udp, Stream}Channel` | Per-transport I/O strategy used by `ServerConnection` | + +## Start here + +- **[Installation](Installation.md)** — composer, requirements, optional extensions. +- **[Quick Start](Quick-Start.md)** — bind, accept, echo in under 20 lines. +- **[Architecture](Architecture.md)** — how the factory, channels, loop and connections fit together. + +## Transports + +- **[Transport TCP](Transport-TCP.md)** — stream-oriented sockets, `ext-sockets` backend. +- **[Transport UDP](Transport-UDP.md)** — datagram sockets with per-peer routing. +- **[Transport TLS](Transport-TLS.md)** — `tls://` streams, modern handshake. +- **[Transport SSL](Transport-SSL.md)** — `ssl://` streams, legacy fallback. + +## API + +- **[Server Lifecycle](Server-Lifecycle.md)** · **[Client Lifecycle](Client-Lifecycle.md)** — what each method does and when. +- **[Connection and Channel](Connection-and-Channel.md)** — the per-accepted-client object and its strategy. +- **[Event Loop Integration](Event-Loop-Integration.md)** — embedding the server in your own loop with `tick()`. +- **[API Reference](API-Reference.md)** — single-page method matrix. +- **[Enums](Enums.md)** · **[Exceptions](Exceptions.md)** · **[SSL Context Options](SSL-Context-Options.md)** + +## Recipes + +- **[Recipe Echo Server](Recipe-Echo-Server.md)** — minimal TCP / UDP echo. +- **[Recipe Chat Server](Recipe-Chat-Server.md)** — registered clients + targeted broadcast. +- **[Recipe SMTP Client](Recipe-SMTP-Client.md)** — raw `EHLO` over implicit TLS. +- **[Recipe Broadcast](Recipe-Broadcast.md)** — fan-out to all / by-id / by-list. +- **[Recipe Self Signed TLS](Recipe-Self-Signed-TLS.md)** — generate a cert, bind a TLS server, connect from a client. +- **[Recipe Custom Channel](Recipe-Custom-Channel.md)** — write your own transport strategy. + +## Operational + +- **[Testing Strategy](Testing-Strategy.md)** — unit + integration patterns we use ourselves. +- **[Migration Guide](Migration-Guide.md)** — moving from 1.x to 2.x. +- **[FAQ](FAQ.md)** — common questions and gotchas. + +--- + +> 2.x line · PHP 8.2+ · MIT · [GitHub](https://github.com/InitPHP/Socket) · [Packagist](https://packagist.org/packages/initphp/socket) diff --git a/docs/Installation.md b/docs/Installation.md new file mode 100644 index 0000000..65eacf4 --- /dev/null +++ b/docs/Installation.md @@ -0,0 +1,56 @@ +# Installation + +## Composer + +```bash +composer require initphp/socket +``` + +The package follows [Semantic Versioning](https://semver.org/). The current major is **2.x**. + +```json +{ + "require": { + "initphp/socket": "^2.0" + } +} +``` + +## Requirements + +| Requirement | Version | Why | +|---|---|---| +| **PHP** | `^8.2` | The package uses enums, `readonly` promoted properties, intersection types and other modern PHP features. | +| **ext-sockets** | bundled in PHP | Backs the TCP and UDP transports (`socket_create`, `socket_bind`, …). | +| **ext-openssl** | bundled in PHP | Powers the `tls://` and `ssl://` stream wrappers. | + +> **Heads-up:** `ext-sockets` ships with PHP but is occasionally disabled in shared hosting builds. Run `php -m | grep sockets` if you are not sure. + +## Optional extensions + +| Extension | Purpose | +|---|---| +| **ext-pcntl** | Required only to run the package's TLS integration test suite (the test forks a child process for the client side of the handshake). Production code never depends on it. | +| **ext-pcov** *or* **ext-xdebug** | Code coverage when running the test suite. CI uses pcov for speed. | + +## Verifying the install + +A one-liner that exercises both the factory and the runtime: + +```php +require __DIR__ . '/vendor/autoload.php'; + +use InitPHP\Socket\Socket; +use InitPHP\Socket\Enum\Transport; + +$server = Socket::server(Transport::TCP, '127.0.0.1', 9000); +echo get_class($server), PHP_EOL; +// InitPHP\Socket\Server\TCP +``` + +If that prints the class name, your install is good. No socket was bound; the factory returns a configured-but-passive server. + +## Next steps + +- Run the [Quick Start](Quick-Start.md) for an end-to-end echo example. +- Skim the [Architecture](Architecture.md) page if you want to understand how the pieces fit together before reading the API. diff --git a/docs/Migration-Guide.md b/docs/Migration-Guide.md new file mode 100644 index 0000000..d14888d --- /dev/null +++ b/docs/Migration-Guide.md @@ -0,0 +1,157 @@ +# Migration Guide — 1.x → 2.x + +2.x is a clean break from 1.x. The previous server loop had race conditions, lost inbound data through its liveness check, and stored transport state on a `static` property that leaked between instances. Fixing those needed API changes, so 2.x ships with a new shape rather than a back-compat shim. + +This guide is a step-by-step upgrade. The public surface stays small, so the work is mechanical. + +## Requirements + +| Aspect | 1.x | 2.x | +|---|---|---| +| PHP | `>=7.4` | `^8.2` (2.0.0 itself required `^8.1`) | +| Required extensions | `ext-sockets` | `ext-sockets`, `ext-openssl` | +| CI tested versions | n/a | 8.2, 8.3, 8.4, 8.5 | + +## Factory + +The integer constants are gone. The `Transport` enum takes their place, and the mystery `$argument` parameter is split into two explicit named parameters: + +```diff +- use InitPHP\Socket\Socket; ++ use InitPHP\Socket\Socket; ++ use InitPHP\Socket\Enum\{Transport, Domain}; + +- $server = Socket::server(Socket::TCP, '127.0.0.1', 8080); ++ $server = Socket::server(Transport::TCP, '127.0.0.1', 8080); + +- $server = Socket::server(Socket::TCP, '127.0.0.1', 8080, 'v6'); ++ $server = Socket::server(Transport::TCP, '127.0.0.1', 8080, Domain::V6); + +- $server = Socket::server(Socket::TLS, '127.0.0.1', 8443, 5.0); ++ $server = Socket::server(Transport::TLS, '127.0.0.1', 8443, timeout: 5.0); +``` + +## Server method renames + +| 1.x | 2.x | Notes | +|---|---|---| +| `connection()` | `listen()` | More accurate — accept happens later. | +| `disconnect()` | `close()` | Same shape, more accurate name. | +| `live(callable, int $usleep = 100000)` | `live(callable, float $idleSeconds = 0.05)` | Same idea, now in seconds. | +| `wait(int\|float $seconds)` | `wait(float $seconds)` | Sub-second precision via one float. | +| `clientRegister($id, $conn)` | `register($id, $conn)` | Promoted to the interface. | +| `broadcast($message, $clients = null)` | `broadcast(string $message, int\|string\|array\|null $ids = null)` | Always returns `bool`. | + +New on `SocketServerInterface`: + +- `tick(callable, float = 0.0): int` — single-iteration accept/dispatch. +- `stop(): void` — cooperative exit from `live()`. +- `isRunning(): bool` — query the loop flag. + +## `ServerClient` → `ServerConnection` + +The per-accepted-connection class is renamed and rebuilt: + +| 1.x: `Server\ServerClient` | 2.x: `Server\ServerConnection` | +|---|---| +| `push(string $msg)` | `write(string $data): ?int` | +| `read(int $len, ?int $type = null)` | `read(int $len = 1024): ?string` | +| `close(): bool` | `close(): bool` | +| `isDisconnected(): bool` (**consumed data!**) | `isAlive(): bool` (non-destructive) | +| `getSocket()` returns mixed | `getSocket(): mixed`, plus `getChannel(): ChannelInterface` | +| `__setSocket()` magic | gone — channels are constructed normally | +| `static $credentials` shared state | gone — every connection owns its own `Channel` | + +The most important behavioural change: **`isAlive()` does not read data off the wire.** If your 1.x code relied on `isDisconnected()` to both check liveness **and** consume the next line, you now need to call `read()` explicitly. + +```diff +- if ($conn->isDisconnected()) { continue; } +- // (data already silently read by isDisconnected and discarded) ++ if (!$conn->isAlive()) { continue; } ++ $line = $conn->read(1024); ++ if ($line !== null) { ++ // ... handle line ... ++ } +``` + +## Client method renames + +| 1.x | 2.x | +|---|---| +| `connection()` | `connect()` | +| `disconnect()` | `disconnect()` (unchanged) | +| `read()` / `write()` | `read()` / `write()` (return `null` instead of `false` on failure) | + +## Exceptions + +The shape changed: + +- `SocketException` now extends `\RuntimeException` (was `\Exception`). +- `SocketConnectionException` and `SocketListenException` extend `SocketException` (were `\Exception` directly). +- A new marker interface `SocketExceptionInterface` is implemented by every package exception, including `SocketInvalidArgumentException`. + +```diff +- try { /* ... */ } catch (\InitPHP\Socket\Exception\SocketException $e) { /* ... */ } ++ try { /* ... */ } catch (\InitPHP\Socket\Exception\SocketExceptionInterface $e) { /* ... */ } +``` + +The 1.x `SocketInvalidArgumentException` was disjoint from `SocketException`. In 2.x the marker interface unifies them. + +## Removed traits and base classes + +The `Common/` namespace is gone. If you were extending or composing the 1.x base types, switch to the new abstracts: + +| 1.x | 2.x | +|---|---| +| `Common\BaseClient` | `Client\AbstractClient` | +| `Common\BaseServer` | `Server\AbstractServer` | +| `Common\StreamClientTrait` | `Client\AbstractStreamClient` | +| `Common\StreamServerTrait` | `Server\AbstractStreamServer` | +| `Common\BaseCommon` / `Common\ServerTrait` | merged into the abstracts | + +## Domain selection + +The 1.x string-typed `$argument` is now the `Domain` enum: + +```diff +- Socket::server(Socket::TCP, '127.0.0.1', 8080, 'v4'); ++ Socket::server(Transport::TCP, '127.0.0.1', 8080, Domain::V4); + +- Socket::server(Socket::UDP, '/tmp/x.sock', 0, 'unix'); ++ Socket::server(Transport::UDP, '/tmp/x.sock', 1, Domain::UNIX); +``` + +For `Domain::UNIX`, the constructor still demands `port >= 1`. Pass any non-zero placeholder; the kernel ignores the port for UDS. + +## Crypto methods + +1.x used lower-case strings (`'tls'`, `'tlsv1.2'`, `'sslv23'`). 2.x uses the `CryptoMethod` enum: + +```diff +- $server->crypto('tlsv1.2'); ++ $server->crypto(\InitPHP\Socket\Enum\CryptoMethod::TLSv1_2); + +- $server->crypto(null); ++ $server->crypto(null); // still allowed — clears the override +``` + +`CryptoMethod::fromName('TLSv1.2')` parses a config-file string into an enum case if you can't hard-code the case. + +## Quick migration checklist + +1. Bump `php` to `^8.2` in your project's `composer.json`. Add `ext-openssl` if you don't already require it. +2. Replace every `Socket::TCP` / `UDP` / `TLS` / `SSL` reference with the matching `Transport` enum case. +3. Replace the third "argument" parameter on factory calls with `Domain::*` (TCP / UDP) or `timeout:` (TLS / SSL). +4. Rename `connection()` → `listen()` (server) or `connect()` (client). +5. Rename `disconnect()` → `close()` on servers (clients keep `disconnect()`). +6. Rename `ServerClient` references to `ServerConnection`, `push()` to `write()`. +7. Audit every call to `isDisconnected()` — switch to `isAlive()` and read data explicitly. **This is the most important step.** +8. Move 1.x `Common\*` base classes to the new abstracts under `Server\` / `Client\`. +9. Switch crypto string arguments to `CryptoMethod` enum cases. +10. Catch `SocketExceptionInterface` instead of (or in addition to) `SocketException` if you want a single catch site. + +## See also + +- **[Architecture](Architecture.md)** — the new layered design. +- **[Server Lifecycle](Server-Lifecycle.md)** — `listen` / `live` / `tick` / `close` semantics. +- **[Connection and Channel](Connection-and-Channel.md)** — the new per-accepted-client object. diff --git a/docs/Quick-Start.md b/docs/Quick-Start.md new file mode 100644 index 0000000..95ba286 --- /dev/null +++ b/docs/Quick-Start.md @@ -0,0 +1,127 @@ +# Quick Start + +A complete TCP echo server, a matching client, and a five-minute tour of the API. + +## A working server + +Create `server.php`: + +```php +listen(); + +echo "Listening on 127.0.0.1:9000\n"; + +$server->live(function (SocketServerInterface $srv, SocketConnectionInterface $conn) { + $payload = $conn->read(1024); + if ($payload === null) { + return; + } + $conn->write("echo: {$payload}"); +}); +``` + +Run it: + +```bash +php server.php +``` + +## A working client + +Create `client.php`: + +```php +connect(); + +$client->write("hello\n"); +echo $client->read(1024); // -> "echo: hello\n" + +$client->disconnect(); +``` + +Run it from a second terminal: + +```bash +php client.php +``` + +You will see `echo: hello` printed back. The server keeps running until you stop it (Ctrl-C). You can also connect with `nc 127.0.0.1 9000` to talk to it interactively. + +## What just happened + +The factory built a concrete `Server\TCP` instance, `listen()` bound and started listening, and `live()` ran a non-blocking accept/dispatch loop that calls the callback whenever a connection has new inbound data. + +``` +Socket::server(Transport::TCP, ...) + │ + ▼ + Server\TCP ┌──────────────────────────────┐ + │ listen() → │ socket_create + bind + listen│ + │ live() → │ while (running) { tick(); } │ + │ tick() → │ socket_select + accept │ + ▼ │ dispatch readable clients │ + ServerConnection └──────────────────────────────┘ + │ + ▼ + TcpChannel (read / write / isAlive / close) +``` + +## Switching transports + +The same factory shape works for every transport — only the enum case changes: + +```php +Socket::server(Transport::TCP, '127.0.0.1', 9000); +Socket::server(Transport::UDP, '127.0.0.1', 9001); +Socket::server(Transport::TLS, '127.0.0.1', 9443, timeout: 5.0) + ->option('local_cert', __DIR__ . '/server.pem'); +Socket::server(Transport::SSL, '127.0.0.1', 9444, timeout: 5.0) + ->option('local_cert', __DIR__ . '/server.pem'); +``` + +Clients mirror servers: + +```php +Socket::client(Transport::TCP, '127.0.0.1', 9000); +Socket::client(Transport::UDP, '127.0.0.1', 9001); +Socket::client(Transport::TLS, 'example.com', 443, timeout: 5.0) + ->option('cafile', '/etc/ssl/certs/ca-certificates.crt'); +``` + +## Tick instead of live + +`live()` is just `while ($this->isRunning()) $this->tick(...)`. If your application already has an event loop, drive the server from there: + +```php +$server->listen(); + +while ($app->running) { + $events = $server->tick(fn ($srv, $conn) => /* … */, waitSeconds: 0.0); + if ($events === 0) { + $app->yield(); + } +} +``` + +See [Event Loop Integration](Event-Loop-Integration.md) for the details. + +## Where to next + +- **[Architecture](Architecture.md)** — the model. +- **[Server Lifecycle](Server-Lifecycle.md)** — what `listen` / `live` / `tick` / `close` actually do. +- **[Recipe Chat Server](Recipe-Chat-Server.md)** — a richer end-to-end example with `register()` and `broadcast()`. diff --git a/docs/Recipe-Broadcast.md b/docs/Recipe-Broadcast.md new file mode 100644 index 0000000..ec0ce66 --- /dev/null +++ b/docs/Recipe-Broadcast.md @@ -0,0 +1,103 @@ +# Recipe — Broadcast + +`broadcast()` is the package's fan-out primitive. The same method covers three patterns; the right one is selected by the type of the second argument. + +```php +public function broadcast( + string $message, + int|string|array|null $clients = null, +): bool; +``` + +| `$clients` | Reach | +|---|---| +| `null` | Every alive client. | +| `int|string` | The one client previously `register()`-ed with this id. Silently no-ops if no such id is mapped. | +| `array` | The clients matching any of the supplied ids. Unknown ids are skipped. | + +Return value: `true` if the dispatch completed (even when zero clients matched). `false` only if something in the loop raised — which the package internally swallows to keep `live()` resilient. + +## All connected clients + +```php +$server->live(function ($srv, $conn) { + $payload = $conn->read(); + if ($payload !== null) { + $srv->broadcast($payload); // everyone sees the bytes the sender posted + } +}); +``` + +`isAlive()` is checked per recipient before `write()`. Dead connections in the registry are skipped silently and evicted on the next loop iteration. + +## A single named client + +```php +$server->live(function ($srv, $conn) { + $line = trim((string) $conn->read()); + if (preg_match('/^TO\s+(\S+)\s+(.+)$/', $line, $m)) { + $srv->broadcast($m[2], $m[1]); // single id + } +}); +``` + +If `$m[1]` is not mapped (nobody registered with that name), the call is a no-op. + +## A list of named clients + +```php +$srv->broadcast("⚠ maintenance window starts in 10 min", ['admin', 'oncall', 'sre']); +``` + +The package iterates the list, looks each id up in `clientIdMap`, and writes to each match. Unknown ids cost nothing. + +## Iterating manually + +For anything not covered by the three modes — sending to clients filtered by an arbitrary predicate, for example — use `getClients()` directly: + +```php +$server->live(function ($srv, $conn) { + if ($conn->read() !== 'hello vips') { + return; + } + foreach ($srv->getClients() as $id => $other) { + if (is_string($id) && str_starts_with($id, 'vip-')) { + $other->write("hi VIP {$id}\n"); + } + } +}); +``` + +`getClients()` returns a map keyed by registered id (string) **or** the server's internal numeric key for clients that never registered. See [Connection and Channel](Connection-and-Channel.md) for the identity contract. + +## UDP broadcasting + +UDP has the same `broadcast()` shape but with caveats: + +- A peer is "known" only after speaking once — there is no discovery. +- Each `write()` is a separate `socket_sendto`; the kernel may drop any one of them. +- `isAlive()` on a UDP connection is application-level — the server keeps writing to peers it has not heard from until you `close()` them. + +```php +$server = Socket::server(Transport::UDP, '0.0.0.0', 9000); +$server->listen(); + +$server->live(function ($srv, $conn) { + $payload = $conn->read(65535); + if ($payload === 'ANNOUNCE') { + $srv->broadcast('hello room', null); + } +}); +``` + +## Order, atomicity, error handling + +- **Order** — clients receive messages in the order they were registered. There is no priority queue. +- **Atomicity** — broadcast is per-recipient `write()`. If the OS buffers fill mid-loop, that recipient's write may be short or fail; others continue. +- **Error handling** — `broadcast()` catches `Throwable` and returns `false`. The wrap exists so a misbehaving channel cannot kill the loop. Inspect the return value when you care. + +## See also + +- **[Recipe Chat Server](Recipe-Chat-Server.md)** — broadcast in a richer protocol context. +- **[Server Lifecycle](Server-Lifecycle.md)** — when `broadcast()` is a no-op (before `listen()`, after `close()`). +- **[Connection and Channel](Connection-and-Channel.md)** — identity and the `clientIdMap`. diff --git a/docs/Recipe-Chat-Server.md b/docs/Recipe-Chat-Server.md new file mode 100644 index 0000000..e74261f --- /dev/null +++ b/docs/Recipe-Chat-Server.md @@ -0,0 +1,155 @@ +# Recipe — Chat Server + +A TCP server that supports named clients and directed messages. The protocol is line-oriented: + +| Command | Effect | +|---|---| +| `REGISTER alice` | Claim the name `alice` for the rest of the session. | +| `SEND @bob hello bob` | Direct-message `bob`. | +| `quit` / `exit` | Disconnect. | +| anything else | Broadcast to every connected client. | + +## Server + +`chat-server.php`: + +```php +listen(); + +echo "Chat server listening on 127.0.0.1:8080\n"; + +$server->live(function (SocketServerInterface $srv, SocketConnectionInterface $conn) { + $line = $conn->read(4096); + if ($line === null) { + return; + } + $line = trim($line); + if ($line === '') { + return; + } + + if (in_array($line, ['quit', 'exit'], true)) { + $conn->write("Goodbye!\n"); + $conn->close(); + return; + } + + if (preg_match('/^REGISTER\s+([\w-]{3,})$/i', $line, $m) === 1) { + $srv->register($m[1], $conn); + $conn->write("Registered as {$m[1]}\n"); + return; + } + + if (preg_match('/^SEND\s+@([\w-]+)\s+(.+)$/i', $line, $m) === 1) { + $sender = $conn->getId() ?? 'guest'; + $srv->broadcast("[{$sender} → {$m[1]}] {$m[2]}\n", $m[1]); + return; + } + + $sender = $conn->getId() ?? 'guest'; + $srv->broadcast("[{$sender}] {$line}\n"); +}); +``` + +## Try it + +Run the server: + +```bash +php chat-server.php +``` + +Open two more terminals and connect with `nc`: + +```text +$ nc 127.0.0.1 8080 # terminal A +REGISTER alice +Registered as alice + +$ nc 127.0.0.1 8080 # terminal B +REGISTER bob +Registered as bob +SEND @alice hey there + # terminal A sees: + # [bob → alice] hey there + +hello room # terminal B + # both terminals see: + # [bob] hello room +``` + +## How it works + +### Registering an id + +`SocketServerInterface::register(int|string, SocketConnectionInterface)` does two things: + +1. Calls `setId()` on the connection so future code can identify it. +2. Updates the server's internal `clientIdMap` so `broadcast()` can address the connection by id. + +Until `register()` is called, `$conn->getId()` returns `null` and `broadcast(msg, 'alice')` will skip the connection. + +### Broadcasting + +`broadcast()` accepts three shapes: + +```php +$srv->broadcast('mass'); // every alive client +$srv->broadcast('alice-only', 'alice'); // single id +$srv->broadcast('vips', ['alice','bob']); // multiple ids +``` + +Unknown ids are silently skipped — the loop short-circuits with a `isset($this->clientIdMap[$id])` check. + +### `close()` from inside the callback + +`$conn->close()` is safe to call from inside the callback. The server's loop checks `isAlive()` on every iteration before invoking the callback, so the closed connection is evicted on the next `tick()` and never receives a message again. + +### Race-condition note + +The "register" workflow is application-level — the server does not enforce uniqueness, nor does it verify the registering client is the rightful owner of the name. Add your own auth on top if that matters. + +## Variations + +### Refuse unregistered users from broadcasting + +```php +if ($conn->getId() === null) { + $conn->write("REGISTER first.\n"); + return; +} +``` + +Slot that at the top of the broadcast branches. + +### Per-room dispatch + +`register()` accepts both `int` and `string`. Use composite ids like `"room1#alice"` and target a room with a list: + +```php +$srv->broadcast('hi room', array_filter( + array_map( + fn ($c) => $c->getId(), + $srv->getClients(), + ), + fn ($id) => is_string($id) && str_starts_with($id, 'room1#'), +)); +``` + +### Drop dead peers proactively + +The server already evicts disconnected clients on the next loop iteration. To do it more eagerly (e.g. when running this on UDP where there is no kernel close signal), call `$conn->isAlive()` in your callback and `$conn->close()` if you decide the peer is gone. + +## See also + +- **[Recipe Broadcast](Recipe-Broadcast.md)** — the dispatch patterns isolated. +- **[Connection and Channel](Connection-and-Channel.md)** — what `setId()` / `getId()` actually do. +- **[Server Lifecycle](Server-Lifecycle.md)** — `register()` / `broadcast()` semantics across states. diff --git a/docs/Recipe-Custom-Channel.md b/docs/Recipe-Custom-Channel.md new file mode 100644 index 0000000..e06c48a --- /dev/null +++ b/docs/Recipe-Custom-Channel.md @@ -0,0 +1,155 @@ +# Recipe — Custom Channel + +`ChannelInterface` is the strategy seam for transport-specific I/O. Implementing your own opens the package to anything you can read from and write to — an in-process pipe, a Redis pub/sub channel, a fake for tests, a custom binary framing on top of an existing socket. + +## The contract + +```php +namespace InitPHP\Socket\Interfaces; + +interface ChannelInterface +{ + public function read(int $length = 1024, ?int $flag = null): ?string; + public function write(string $data): ?int; + public function close(): bool; + public function isAlive(): bool; + public function getResource(): mixed; +} +``` + +Five methods. No setup, no teardown, no lifecycle hooks — `__construct` is yours to shape. + +## Example: in-memory channel + +A channel backed by two PHP strings. The most useful shape for unit tests: you put bytes into one direction and read them from the other. + +```php +namespace App\Net; + +use InitPHP\Socket\Interfaces\ChannelInterface; + +final class InMemoryChannel implements ChannelInterface +{ + private string $inbound = ''; // what the channel reads + private string $outbound = ''; // what the channel writes + private bool $alive = true; + + public function pushInbound(string $data): void { $this->inbound .= $data; } + public function drainOutbound(): string { $b = $this->outbound; $this->outbound = ''; return $b; } + + public function read(int $length = 1024, ?int $flag = null): ?string + { + if ($this->inbound === '' || $length < 1) { + return null; + } + $chunk = substr($this->inbound, 0, $length); + $this->inbound = substr($this->inbound, strlen($chunk)); + return $chunk; + } + + public function write(string $data): ?int + { + if (!$this->alive) { + return null; + } + $this->outbound .= $data; + return strlen($data); + } + + public function close(): bool { $this->alive = false; return true; } + public function isAlive(): bool { return $this->alive; } + public function getResource(): mixed { return null; } +} +``` + +Now wrap it in a `ServerConnection` and use it anywhere a real connection would work: + +```php +use InitPHP\Socket\Server\ServerConnection; + +$channel = new InMemoryChannel(); +$conn = new ServerConnection($channel); + +$channel->pushInbound("hello\n"); + +echo $conn->read(1024); // "hello\n" + +$conn->write("hi back\n"); +echo $channel->drainOutbound(); // "hi back\n" +``` + +This is exactly how the package's [Testing Strategy](Testing-Strategy.md) exercises broadcast and registry logic without binding any real ports. + +## Example: line-framing decorator + +A channel that wraps another channel and only returns complete `\n`-terminated lines from `read()`. Everything else passes through. + +```php +namespace App\Net; + +use InitPHP\Socket\Interfaces\ChannelInterface; + +final class LineFramingChannel implements ChannelInterface +{ + private string $rxBuffer = ''; + + public function __construct(private readonly ChannelInterface $inner) {} + + public function read(int $length = 1024, ?int $flag = null): ?string + { + // Pull as much as possible from the inner channel into the buffer. + while (true) { + $more = $this->inner->read($length, $flag); + if ($more === null) { + break; + } + $this->rxBuffer .= $more; + } + $pos = strpos($this->rxBuffer, "\n"); + if ($pos === false) { + return null; + } + $line = substr($this->rxBuffer, 0, $pos + 1); + $this->rxBuffer = substr($this->rxBuffer, $pos + 1); + return $line; + } + + public function write(string $data): ?int { return $this->inner->write($data); } + public function close(): bool { return $this->inner->close(); } + public function isAlive(): bool { return $this->inner->isAlive(); } + public function getResource(): mixed { return $this->inner->getResource(); } +} +``` + +Use it by wrapping the channel a real `ServerConnection` carries: + +```php +$server->live(function ($srv, $conn) { + $framed = new LineFramingChannel($conn->getChannel()); + while (($line = $framed->read(4096)) !== null) { + // ... handle one whole line ... + } +}); +``` + +## What to remember + +- **`read()` must not raise.** Return `null` for "nothing right now" or "broken". Raising bubbles up into `live()` / `tick()` and the package only swallows it inside `broadcast()`. +- **`write()` returns bytes written.** A short write (`strlen($data) > $written`) is still a success — the caller decides whether to retry. +- **`close()` is idempotent.** Make double-close safe. +- **`isAlive()` is non-destructive.** It must not consume from the underlying transport; the user-callback expects to read those bytes itself. +- **`getResource()` is informational.** Used by `socket_select` / `stream_select` only when the resource is a `\Socket` / stream resource. If your channel has no native handle, return `null` — but then it cannot participate in a real server's read set without a wrapping mechanism. + +## Plugging into a server + +There is no `attachChannel()` on the server. The package owns the accept logic and constructs channels itself. Hooks that fit your channel: + +- **Subclass `AbstractServer`** and override `tick()` to build your own channels. +- **Wrap an existing connection's channel** post-accept, like `LineFramingChannel` above. +- **Skip the server entirely** and use channels as standalone I/O objects in your own code. + +## See also + +- **[Architecture](Architecture.md)** — where channels sit in the layering. +- **[Connection and Channel](Connection-and-Channel.md)** — the existing `Tcp` / `Udp` / `Stream` channels. +- **[Testing Strategy](Testing-Strategy.md)** — fake channels in unit tests. diff --git a/docs/Recipe-Echo-Server.md b/docs/Recipe-Echo-Server.md new file mode 100644 index 0000000..717f955 --- /dev/null +++ b/docs/Recipe-Echo-Server.md @@ -0,0 +1,136 @@ +# Recipe — Echo Server + +The smallest server that demonstrates accept, read and write. We do it twice — once over TCP, once over UDP — so the differences are visible side by side. + +## TCP echo + +`tcp-echo-server.php`: + +```php +listen(); + +echo "TCP echo on 127.0.0.1:9000\n"; + +$server->live(function (SocketServerInterface $srv, SocketConnectionInterface $conn) { + $payload = $conn->read(1024); + if ($payload === null) { + return; + } + $conn->write("echo: {$payload}"); +}); +``` + +```bash +php tcp-echo-server.php +``` + +From another terminal: + +```bash +$ nc 127.0.0.1 9000 +hi +echo: hi +``` + +### A matching TCP client + +`tcp-echo-client.php`: + +```php +connect(); + +$client->write("hello\n"); +echo $client->read(1024); // -> "echo: hello\n" + +$client->disconnect(); +``` + +## UDP echo + +`udp-echo-server.php`: + +```php +listen(); + +echo "UDP echo on 127.0.0.1:9001\n"; + +$server->live(function (SocketServerInterface $srv, SocketConnectionInterface $conn) { + $payload = $conn->read(65535); + if ($payload === null) { + return; + } + $conn->write("echo: {$payload}"); +}); +``` + +```bash +php udp-echo-server.php +``` + +From another terminal: + +```bash +$ echo -n 'ping' | nc -u -w1 127.0.0.1 9001 +echo: ping +``` + +### A matching UDP client + +`udp-echo-client.php`: + +```php +connect(); + +$client->write('ping'); +echo $client->read(65535); + +$client->disconnect(); +``` + +## What changes between TCP and UDP + +- The transport enum case (`TCP` vs `UDP`). +- Read buffer size: 1 KiB is plenty for ad-hoc TCP framing; UDP needs to be big enough for one whole datagram (`UdpChannel::MAX_DATAGRAM = 65535`). +- UDP has no half-close and no notion of disconnection on the server side. If a client stops talking, the server still keeps its `UdpChannel`. Evict idle peers with an application-level TTL — see [Transport UDP](Transport-UDP.md). + +## What stays the same + +- Lifecycle: `listen()` → `live(callback)` → `close()` (clean shutdown). +- The callback signature `(SocketServerInterface, SocketConnectionInterface)`. +- `$conn->read()` returns `?string`, `$conn->write()` returns `?int`. + +## See also + +- **[Transport TCP](Transport-TCP.md)** / **[Transport UDP](Transport-UDP.md)** — transport-specific details. +- **[Recipe Broadcast](Recipe-Broadcast.md)** — fan out a message to multiple peers. +- **[Event Loop Integration](Event-Loop-Integration.md)** — drive the same server from `tick()` instead of `live()`. diff --git a/docs/Recipe-SMTP-Client.md b/docs/Recipe-SMTP-Client.md new file mode 100644 index 0000000..0807cc0 --- /dev/null +++ b/docs/Recipe-SMTP-Client.md @@ -0,0 +1,103 @@ +# Recipe — SMTP Client (raw) + +A minimal raw SMTP client that opens an implicit-TLS connection to Gmail's port 465 and performs the initial `EHLO` exchange. Useful as a smoke test for the TLS client and to learn the protocol; **do not** ship this as a real mailer — use `initphp/mailer` or another battle-tested library for that. + +## The script + +`smtp-probe.php`: + +```php +option('verify_peer', false) + ->option('verify_peer_name', false); + +$client->connect(); + +echo $client->read(1024); // 220 banner +$client->write("EHLO localhost\r\n"); +echo $client->read(1024); // 250 capabilities +$client->write("QUIT\r\n"); +echo $client->read(1024); // 221 closing + +$client->disconnect(); +``` + +```bash +php smtp-probe.php +``` + +Expected output (truncated): + +``` +220 smtp.gmail.com ESMTP … +250-smtp.gmail.com at your service, … +250-SIZE … +250-STARTTLS +250 SMTPUTF8 +221 2.0.0 closing connection +``` + +## Why these knobs + +- **`Transport::SSL`** — Gmail's port 465 serves implicit TLS; the connection is encrypted from the first byte. For port 587 you would start with `Transport::TCP` and upgrade in place with `crypto()` after `STARTTLS`. +- **`timeout: 10.0`** — the connect (and TLS handshake) must finish inside this budget. +- **`verify_peer`** is set to `false` here to keep the snippet self-contained. **In production** point `cafile` at the system trust store (`/etc/ssl/certs/ca-certificates.crt` on Debian/Ubuntu, `/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem` on RHEL/Alma) and leave `verify_peer` on. + +## Reading SMTP responses cleanly + +SMTP replies are line-oriented and may span multiple lines for one logical response (`250-foo` continuation, `250 bar` final). Looping until the final-line marker shows up makes the read robust: + +```php +function smtpRead(\InitPHP\Socket\Interfaces\SocketClientInterface $client): string +{ + $out = ''; + while (($chunk = $client->read(1024)) !== null) { + $out .= $chunk; + // RFC 5321: final line of a multi-line response uses "". + if (preg_match('/^\d{3} [^\r\n]*\r?\n$/m', $chunk) === 1) { + break; + } + } + return $out; +} +``` + +Use it in place of the raw `$client->read(1024)` calls in the script above. + +## A real STARTTLS flow (port 587) + +For SMTP submission over `STARTTLS`, the protocol starts unencrypted and upgrades: + +```php +use InitPHP\Socket\Enum\{Transport, CryptoMethod}; + +$client = Socket::client(Transport::TCP, 'smtp.example.com', 587, /* no TLS yet */); +$client->connect(); +// 220 banner... +echo $client->read(1024); + +$client->write("EHLO localhost\r\n"); +echo $client->read(1024); + +$client->write("STARTTLS\r\n"); +echo $client->read(1024); +// 220 Ready to start TLS +``` + +> The package's `Client\TCP` does not expose a TLS upgrade — `crypto()` lives on the stream-backed clients (`TLS` / `SSL`). For a true STARTTLS flow you would call PHP's `stream_socket_enable_crypto($client->getSocket(), true, STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT)` directly on the underlying socket. Or open with `Transport::TLS` and use `crypto()` once connected if your peer accepts the deferred handshake. + +## Building this into a sender + +For production mail handling, use a mail library that knows about AUTH, MIME, headers and retries. The example above is a probe — it just shows that the TLS client connects and reads SMTP greetings. See `initphp/mailer` for the full client. + +## See also + +- **[Transport TLS](Transport-TLS.md)** / **[Transport SSL](Transport-SSL.md)** — reference for the stream-backed clients. +- **[SSL Context Options](SSL-Context-Options.md)** — every key `option()` accepts. +- **[Recipe Self Signed TLS](Recipe-Self-Signed-TLS.md)** — local-loopback equivalent for testing. diff --git a/docs/Recipe-Self-Signed-TLS.md b/docs/Recipe-Self-Signed-TLS.md new file mode 100644 index 0000000..ad58da1 --- /dev/null +++ b/docs/Recipe-Self-Signed-TLS.md @@ -0,0 +1,139 @@ +# Recipe — Self-Signed TLS + +Generate a certificate from PHP, bind a TLS server, and connect with a TLS client — all in the same loopback session. Useful for local development and for the package's own integration tests. + +> **Production reminder.** The `verify_peer => false` setup below is for development only. Configure trust with a proper `cafile` / `capath` (or a `peer_fingerprint`) before exposing anything to a real network. + +## Generating the cert in pure PHP + +`mint-cert.php`: + +```php + 2048, + 'private_key_type' => OPENSSL_KEYTYPE_RSA, +]); +$csr = openssl_csr_new(['commonName' => 'localhost'], $pkey); +$x509 = openssl_csr_sign($csr, null, $pkey, days: 1); + +openssl_x509_export($x509, $certPem); +openssl_pkey_export($pkey, $keyPem); + +file_put_contents(__DIR__ . '/server.pem', $certPem . $keyPem); +echo "wrote ", __DIR__, "/server.pem\n"; +``` + +```bash +php mint-cert.php +``` + +You now have a single PEM file containing both the certificate and its private key. The server points its `local_cert` option at this file. + +For a shell-based alternative, `openssl req -x509 …` from the [Transport TLS](Transport-TLS.md) page produces the same shape. + +## A complete TLS round-trip (forked) + +TLS needs concurrent server and client (the handshake is interactive), so the simplest cross-process example forks. `tls-roundtrip.php`: + +```php +option('verify_peer', false) + ->option('verify_peer_name', false) + ->option('allow_self_signed', true); + $client->connect(); + $client->write("hello tls\n"); + + $reply = null; + for ($i = 0; $i < 200 && $reply === null; ++$i) { + $reply = $client->read(1024); + if ($reply === null) usleep(20_000); + } + echo "client received: ", trim((string) $reply), PHP_EOL; + $client->disconnect(); + exit(0); +} + +// ── parent: the server ─────────────────────────────────────── +$server = Socket::server(Transport::TLS, '127.0.0.1', $port, timeout: 2.0) + ->option('local_cert', $certPath) + ->option('allow_self_signed', true); +$server->listen(); + +$received = null; +$deadline = microtime(true) + 5.0; +while ($received === null && microtime(true) < $deadline) { + $server->tick(function ($srv, $conn) use (&$received) { + $payload = $conn->read(1024); + if ($payload !== null) { + $received = $payload; + $conn->write("echo: " . $payload); + } + }, 0.1); +} +$server->close(); + +pcntl_waitpid($pid, $status); +echo "server received: ", trim((string) $received), PHP_EOL; +``` + +Run it: + +```bash +php tls-roundtrip.php +``` + +You should see something like: + +``` +client received: echo: hello tls +server received: hello tls +``` + +## Same-process testing variant + +If your environment does not have `ext-pcntl` (Windows, shared hosting, …) you can still drive the same client/server in tests using the package's `tick()` API. The TLS handshake itself still needs concurrency, so for unit-level coverage you typically: + +- Use a plain `tcp://` socket pair to test the abstract stream client's I/O paths (see [Testing Strategy](Testing-Strategy.md)). +- Use [Recipe Custom Channel](Recipe-Custom-Channel.md) to plug an in-memory channel in place of the real network. + +## Verifying a real CA instead + +When you have a CA-issued cert, the client side simplifies to: + +```php +$client = Socket::client(Transport::TLS, 'api.example.com', 443, timeout: 5.0); +// verify_peer = true is the default; PHP uses the system trust store. +$client->connect(); +``` + +For a private CA, point `cafile` at the trust anchor: + +```php +$client = Socket::client(Transport::TLS, 'private-api.example.com', 443) + ->option('cafile', '/etc/myapp/ca-bundle.pem'); +``` + +## See also + +- **[Transport TLS](Transport-TLS.md)** — protocol-level reference, handshake notes. +- **[SSL Context Options](SSL-Context-Options.md)** — every key `option()` accepts. +- **[Testing Strategy](Testing-Strategy.md)** — how the package's own test suite drives TLS deterministically. diff --git a/docs/Recipes.md b/docs/Recipes.md new file mode 100644 index 0000000..5862d45 --- /dev/null +++ b/docs/Recipes.md @@ -0,0 +1,19 @@ +# Recipes + +Small, runnable end-to-end examples. Each links to a focused page with the full code and explanation. + +| Recipe | Transport | What it shows | +|---|---|---| +| **[Recipe Echo Server](Recipe-Echo-Server.md)** | TCP, UDP | The simplest possible request / response server. | +| **[Recipe Chat Server](Recipe-Chat-Server.md)** | TCP | `register()` for named clients, `broadcast()` for fan-out, `quit` command. | +| **[Recipe Broadcast](Recipe-Broadcast.md)** | TCP & UDP | The three flavours of `broadcast()`: all, by-id, by-list. | +| **[Recipe Self Signed TLS](Recipe-Self-Signed-TLS.md)** | TLS | Generate a cert in pure PHP, bind a TLS server, connect with a TLS client. | +| **[Recipe SMTP Client](Recipe-SMTP-Client.md)** | SSL | Raw `EHLO` exchange against Gmail's port 465. | +| **[Recipe Custom Channel](Recipe-Custom-Channel.md)** | — | Implement your own `ChannelInterface` (in-memory, in-process pipe, …). | + +## Conventions in these recipes + +- Every recipe assumes `composer require initphp/socket` has run and the `vendor/autoload.php` is loaded. +- Loopback (`127.0.0.1`) is used for everything that needs a host so the snippets run unmodified. +- TLS recipes generate self-signed material to keep the snippets self-contained. **Do not ship that** — see [SSL Context Options](SSL-Context-Options.md) for production-grade configuration. +- The recipes prefer `live()` for the canonical pattern. To embed them in your own event loop, swap `live()` for a `while (… $server->tick(…)) { … }` shape — see [Event Loop Integration](Event-Loop-Integration.md). diff --git a/docs/SSL-Context-Options.md b/docs/SSL-Context-Options.md new file mode 100644 index 0000000..6698896 --- /dev/null +++ b/docs/SSL-Context-Options.md @@ -0,0 +1,124 @@ +# SSL Context Options + +The TLS and SSL classes wrap PHP's [SSL context](https://www.php.net/manual/en/context.ssl.php). The fluent `option(string $key, mixed $value)` method writes into the underlying `['ssl' => …]` array passed to `stream_context_create`. + +This page summarises the keys you reach for most often. The PHP manual is the authoritative reference. + +## Server-side keys + +| Key | Type | Purpose | +|---|---|---| +| `local_cert` | `string` (path) | PEM file containing the server certificate (and optionally its private key). Required. | +| `local_pk` | `string` (path) | PEM file with the private key, if not bundled with `local_cert`. | +| `passphrase` | `string` | Passphrase protecting the private key. | +| `cafile` | `string` (path) | CA bundle used when verifying client certificates (mutual TLS). | +| `capath` | `string` (dir) | Hashed CA directory; alternative to `cafile`. | +| `verify_peer` | `bool` (default `true`) | Verify the peer certificate. Leave `true` for mutual TLS. | +| `verify_peer_name` | `bool` (default `true`) | Match the peer cert CN/SAN against the connecting peer name. | +| `allow_self_signed` | `bool` (default `false`) | Accept self-signed certs (development only). | +| `crypto_method` | `int` (`STREAM_CRYPTO_METHOD_*_SERVER`) | Pin a specific cipher family. Prefer `crypto(CryptoMethod::TLSv1_2)`. | +| `ciphers` | `string` | OpenSSL cipher list. | +| `single_dh_use` | `bool` | Use a fresh Diffie-Hellman key for every TLS session. | +| `dh_param` | `string` (path) | Custom DH parameters PEM file. | +| `disable_compression` | `bool` (default `true` since PHP 7) | Disable TLS compression (CRIME mitigation). | +| `peer_fingerprint` | `string|array` | Optional sha256 fingerprint of an expected client cert. | +| `SNI_enabled` | `bool` (default `true`) | Honour Server Name Indication from the client. | + +### Minimal server config + +```php +$server = Socket::server(Transport::TLS, '0.0.0.0', 8443, timeout: 5.0) + ->option('local_cert', '/etc/myapp/server.pem'); +``` + +### Mutual-TLS (client-cert) server + +```php +$server = Socket::server(Transport::TLS, '0.0.0.0', 8443) + ->option('local_cert', '/etc/myapp/server.pem') + ->option('verify_peer', true) + ->option('cafile', '/etc/myapp/ca-bundle.pem') + ->option('verify_peer_name', true); +``` + +## Client-side keys + +| Key | Type | Purpose | +|---|---|---| +| `cafile` | `string` (path) | Trust anchor for verifying the server cert. | +| `capath` | `string` (dir) | Hashed CA directory. | +| `verify_peer` | `bool` (default `true`) | Verify the peer cert. **Keep on in production.** | +| `verify_peer_name` | `bool` (default `true`) | Match cert CN/SAN against the `host` you connected to. | +| `allow_self_signed` | `bool` (default `false`) | Accept self-signed certs (dev / test only). | +| `peer_name` | `string` | Override the name used for `verify_peer_name` matching. Useful when the target hostname differs from the cert CN. | +| `peer_fingerprint` | `string|array` | Expected SHA-256 fingerprint of the server cert (cert pinning). | +| `SNI_enabled` | `bool` (default `true`) | Send Server Name Indication during the handshake. | +| `local_cert` / `local_pk` / `passphrase` | as on server | Client certificate for mutual TLS. | +| `crypto_method` | `int` (`STREAM_CRYPTO_METHOD_*_CLIENT`) | Pin a specific protocol version. Prefer `crypto(CryptoMethod::TLSv1_2)`. | +| `ciphers` | `string` | OpenSSL cipher list. | +| `disable_compression` | `bool` (default `true`) | Disable TLS compression. | + +### Verifying with system CAs + +```php +$client = Socket::client(Transport::TLS, 'example.com', 443, timeout: 5.0); +// PHP will use the OS trust store by default; explicit cafile is only needed +// when you want a custom root. +``` + +### Self-signed development setup + +```php +$client = Socket::client(Transport::TLS, '127.0.0.1', 8443) + ->option('verify_peer', false) + ->option('verify_peer_name', false) + ->option('allow_self_signed', true); +``` + +> **Never ship this configuration.** It is exactly the shape of "accept any certificate", which defeats TLS. Pin a `cafile` or `peer_fingerprint` in production. + +### Mutual-TLS client (client certificate) + +```php +$client = Socket::client(Transport::TLS, 'api.example.com', 443) + ->option('local_cert', '/etc/myapp/client.pem') + ->option('local_pk', '/etc/myapp/client.key') + ->option('passphrase', getenv('CLIENT_KEY_PASS')); +``` + +## Setting crypto_method via the enum + +Two equivalent ways to pin TLS 1.2: + +```php +// Fluent helper (preferred) +$server->crypto(CryptoMethod::TLSv1_2); +$client->crypto(CryptoMethod::TLSv1_2); + +// Raw context option +$server->option('crypto_method', STREAM_CRYPTO_METHOD_TLSv1_2_SERVER); +$client->option('crypto_method', STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT); +``` + +`crypto()` automatically picks the right constant for the side you're on. + +## Where these options end up + +Every `option()` call goes into the array used to build the SSL context: + +```php +// roughly what the package does internally +$context = stream_context_create([ + 'ssl' => $this->options, // everything you set via option() +]); +$stream = stream_socket_client($url, $errNo, $errStr, $timeout, STREAM_CLIENT_CONNECT, $context); +``` + +If a key is not listed above, it still works — `option()` is a pass-through. Anything PHP's SSL context accepts is accepted here. + +## See also + +- **[Transport TLS](Transport-TLS.md)** — `tls://` scheme details. +- **[Transport SSL](Transport-SSL.md)** — `ssl://` scheme details (same options, different defaults). +- **[Enums](Enums.md)** — `CryptoMethod`. +- [PHP manual: SSL context options](https://www.php.net/manual/en/context.ssl.php) diff --git a/docs/Server-Lifecycle.md b/docs/Server-Lifecycle.md new file mode 100644 index 0000000..d995fe1 --- /dev/null +++ b/docs/Server-Lifecycle.md @@ -0,0 +1,148 @@ +# Server Lifecycle + +A server moves through four states. The transitions are explicit — the package never opens a network socket implicitly. + +``` +constructed ──listen()──► listening ──live()/tick()──► running ──stop()──► listening + ──close()──► closed +``` + +## 1. Construct + +```php +use InitPHP\Socket\Socket; +use InitPHP\Socket\Enum\{Transport, Domain}; + +$server = Socket::server(Transport::TCP, '127.0.0.1', 9000, Domain::V4); +``` + +At this point: + +- No network call has been made. +- The host / port arguments are validated synchronously (empty host, port out of 1‒65535 → `SocketInvalidArgumentException`). +- For TLS / SSL the optional `$timeout` argument is stored for the handshake and per-client stream timeout. + +## 2. Listen + +```php +$server->listen(); +``` + +- TCP: `socket_create` → `socket_bind` → `socket_listen` (with `backlog()` if configured). +- UDP: `socket_create` → `socket_bind` (no listen for datagrams). +- TLS / SSL: `stream_socket_server` with the configured SSL context, blocking mode preserved so the handshake during `accept` has room within its timeout. + +After `listen()`: + +- `getSocket()` returns the live listening handle. +- `getClients()` returns `[]` — accept happens inside `live()` / `tick()`, never inside `listen()`. + +Calling `listen()` a second time **throws** `SocketException`. Re-bind a closed server by constructing a fresh instance. + +```php +$server->listen(); +$server->listen(); // ❌ SocketException("Server is already listening.") +``` + +## 3. Run + +Two flavours: the all-in-one loop, or one iteration at a time. + +### `live()` — managed loop + +```php +$server->live(function ($srv, $conn) { + $payload = $conn->read(1024); + if ($payload === null) { + return; + } + $conn->write("echo: {$payload}"); +}, idleSeconds: 0.05); +``` + +- Sets `$running = true`. +- Calls `tick()` in a loop, passing the same `$idleSeconds` as the `select()` timeout. +- Exits when something inside the loop calls `$srv->stop()` (or the process is signalled). + +### `tick()` — single iteration + +```php +$events = $server->tick(callback, waitSeconds: 0.0); +``` + +- Runs one `socket_select` / `stream_select` with the supplied timeout. +- Accepts at most one pending client and services every readable existing connection. +- Returns the number of events handled (0 if no readiness was detected). + +`tick()` is the integration seam for [Event Loop Integration](Event-Loop-Integration.md) and for [deterministic tests](Testing-Strategy.md). + +### What happens per readable resource + +- **Listening socket** → `accept()` a new peer, wrap it in a `Channel`, register it. No callback fires. +- **Existing client** → check `isAlive()`; if dead, close + evict; otherwise call the user callback with `($server, $connection)`. + +UDP differs: there is no `accept()`. Each `tick()` does one `socket_recvfrom`, looks up (or creates) the `UdpChannel` for the source peer, pushes the datagram into its buffer, and invokes the callback. + +## 4. Stop / Close + +`stop()` flips the `$running` flag — the next `tick()` returns and `live()`'s loop exits. It does **not** close any sockets: + +```php +$server->live(function ($srv, $conn) { + if ($conn->read() === 'shutdown') { + $srv->stop(); // exits live() — sockets remain open + } +}); +$server->close(); // tear-down +``` + +`close()` is the destructor: every client connection has `close()` called on it, the registries are emptied, the listening socket is released. It is idempotent — call it as many times as you like, even before `listen()`. + +```php +$server->close(); // ✓ safe before listen() +$server->close(); // ✓ safe to call twice +``` + +After `close()`, `getSocket()` returns `null`. The instance is "done"; create a new one to listen again. + +## Identity and broadcast + +While the loop is running, every connection has a numeric internal key (auto-incremented per accept). You can attach an addressable id with `register()`: + +```php +$server->live(function ($srv, $conn) { + $line = trim((string) $conn->read()); + if (preg_match('/^HELLO (\w+)$/', $line, $m)) { + $srv->register($m[1], $conn); + $conn->write("welcome, {$m[1]}\n"); + } elseif (preg_match('/^TO (\w+) (.+)$/', $line, $m)) { + $srv->broadcast($m[2], $m[1]); // single id + } else { + $srv->broadcast($line); // everybody + } +}); +``` + +See [Recipe Chat Server](Recipe-Chat-Server.md) for the complete walk-through. + +## Method matrix + +| Method | Before `listen()` | After `listen()` | After `close()` | +|---|---|---|---| +| `listen()` | binds | **throws** | binds again is **not** allowed — make a new instance | +| `close()` | no-op (returns `true`) | tears down | no-op (returns `true`) | +| `live()` | **throws** | runs the loop | **throws** | +| `tick()` | **throws** | one iteration | **throws** | +| `stop()` | no-op | flips `$running` | no-op | +| `broadcast()` | no-op (no clients) | dispatches | no-op | +| `register()` | returns `false` (no clients) | maps id to client | returns `false` | +| `getClients()` | `[]` | live map | `[]` | +| `getSocket()` | `null` | listening handle | `null` | +| `getHost()` / `getPort()` | configured value | configured value | configured value | +| `wait(seconds)` | sleeps | sleeps | sleeps | + +## See also + +- **[Client Lifecycle](Client-Lifecycle.md)** — the symmetric model for the connect side. +- **[Event Loop Integration](Event-Loop-Integration.md)** — drive `tick()` from your own scheduler. +- **[Transport TCP](Transport-TCP.md)** / **[Transport UDP](Transport-UDP.md)** / **[Transport TLS](Transport-TLS.md)** / **[Transport SSL](Transport-SSL.md)** — transport-specific quirks of `listen()`. diff --git a/docs/Testing-Strategy.md b/docs/Testing-Strategy.md new file mode 100644 index 0000000..c3dfb38 --- /dev/null +++ b/docs/Testing-Strategy.md @@ -0,0 +1,260 @@ +# Testing Strategy + +The package's own test suite is unit + integration with no mocking framework. This page documents the patterns it uses, so you can extend the suite with the same shapes or borrow them for your own server / client code. + +## How the package's suite is organised + +``` +tests/ +├─ Unit/ # no I/O, no real sockets +│ ├─ Channel/ StreamChannelTest, TcpChannelTest, UdpChannelTest +│ ├─ Client/ AbstractClientTest, AbstractStreamClientTest +│ ├─ Enum/ TransportTest, DomainTest, CryptoMethodTest +│ ├─ Exception/ HierarchyTest +│ ├─ Server/ AbstractServerBroadcastTest, AbstractStreamServerTest, +│ │ ServerConnectionTest, TcpServerOptionsTest, +│ │ UdpServerOptionsTest +│ └─ SocketFactoryTest +└─ Integration/ # real loopback sockets + ├─ IntegrationTestCase.php # shared helpers + ├─ ConnectionErrorsTest.php + ├─ ServerLifecycleTest.php + ├─ StreamClientIoTest.php + ├─ TcpDisconnectTest.php + ├─ TcpEchoTest.php + ├─ TcpServerCloseTest.php + ├─ TlsEchoTest.php # forks the client into a child process + ├─ UdpClientReuseTest.php + ├─ UdpEchoTest.php + └─ UdpServerCloseTest.php +``` + +Numbers as of the 2.0 release: **96 tests · 357 assertions · ≥ 90% line coverage**. + +## Running it + +```bash +composer install +composer test # PHPUnit, unit + integration + +composer test-coverage # same, with Clover output for CI + +composer qa # cs-check + stan + test +``` + +`composer test-coverage` needs **pcov** (or Xdebug). Install pcov via PECL: + +```bash +pecl install pcov # may need brew install pcre2 on macOS for headers +``` + +## Unit patterns + +### Fake channel for in-memory testing + +The `ServerConnection` class is just identity + delegation, so a `FakeChannel` is enough to exercise broadcasting, registry mapping and lifecycle logic: + +```php +final class FakeChannel implements ChannelInterface +{ + public ?string $readReturn = null; + public ?int $writeReturn = null; + public bool $alive = true; + public bool $closed = false; + + /** @var array */ public array $readCalls = []; + /** @var array */ public array $writeCalls = []; + + public function read(int $length = 1024, ?int $flag = null): ?string + { $this->readCalls[] = [$length, $flag]; return $this->readReturn; } + + public function write(string $data): ?int + { $this->writeCalls[] = [$data]; return $this->writeReturn; } + + public function close(): bool { $this->closed = true; return true; } + public function isAlive(): bool { return $this->alive && !$this->closed; } + public function getResource(): mixed { return null; } +} +``` + +Then assert against `writeCalls` / `readCalls` in tests. No fork, no port, no race. + +### Subclassing `AbstractServer` for protected-method coverage + +`addClient()` / `evict()` are protected. The unit test surfaces them via a friend subclass that lives in the same file: + +```php +final class TestableServer extends AbstractServer +{ + public function attach(SocketConnectionInterface $client): int { return $this->addClient($client); } + public function forceEvict(int $key): void { $this->evict($key); } + + public function listen(): static { return $this; } + public function close(): bool { return true; } + public function tick(callable $callback, float $waitSeconds = 0.0): int { return 0; } + public function getSocket(): mixed { return null; } +} +``` + +This lets you exercise `broadcast()` / `register()` / `getClients()` without any real network. + +### Socket pair for channel I/O + +For `TcpChannel`, a `socket_create_pair` gives you two connected, real sockets — perfect for testing reads, writes and `MSG_PEEK`-based liveness without standing up a server: + +```php +$pair = []; +socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $pair); +[$a, $b] = $pair; +socket_set_nonblock($a); +socket_set_nonblock($b); + +$channel = new TcpChannel($a); +$channel->write('hi'); + +$buf = ''; +socket_recv($b, $buf, 1024, MSG_DONTWAIT); +self::assertSame('hi', $buf); +``` + +For `StreamChannel`, `fopen('php://memory', 'r+')` is enough. + +## Integration patterns + +### Ephemeral port via probe + +Tests pick a free port by binding to `0` and reading the assigned port back: + +```php +protected function findFreePort(int $type = SOCK_STREAM): int +{ + $proto = $type === SOCK_STREAM ? SOL_TCP : SOL_UDP; + $sock = socket_create(AF_INET, $type, $proto); + socket_bind($sock, '127.0.0.1', 0); + $addr = ''; $port = 0; + socket_getsockname($sock, $addr, $port); + socket_close($sock); + return $port; +} +``` + +There is a tiny race between this call and the caller's bind, acceptable for loopback test scaffolding. + +### Same-process TCP / UDP round-trip + +TCP and UDP connect over loopback complete at the kernel level, so the test process can be both client and server. Drive the server with `tick()` between client actions: + +```php +$server = new TcpServer('127.0.0.1', $port); $server->listen(); +$client = new TcpClient('127.0.0.1', $port); $client->connect(); + +$server->tick(fn() => null, 0.2); // accept the queued client + +$client->write('hello'); +$server->tick(function ($srv, $conn) use (&$received) { + $received = $conn->read(1024); + $conn->write('echo:' . $received); +}, 0.2); + +self::assertSame('hello', $received); +``` + +### TLS — fork only the client + +The TLS handshake needs concurrency. Coverage tools live in one process, so the **server stays in the parent** and the **client is forked** into a child: + +```php +$pid = pcntl_fork(); +if ($pid === 0) { + usleep(150_000); + $client = Socket::client(Transport::TLS, '127.0.0.1', $port, 2.0) + ->option('verify_peer', false) + ->option('allow_self_signed', true); + $client->connect(); + $client->write('hello-tls'); + // ... read echo ... + $client->disconnect(); + exit(0); +} + +$server = Socket::server(Transport::TLS, '127.0.0.1', $port, 2.0) + ->option('local_cert', $certPath) + ->option('allow_self_signed', true); +$server->listen(); + +while ($received === null && microtime(true) < $deadline) { + $server->tick($echoCallback, 0.1); +} +pcntl_waitpid($pid, $status); +``` + +The package's `TlsEchoTest` is exactly this. Coverage attributes every server line because the server runs in the parent (the PHPUnit process). + +### Self-signed cert as a test helper + +The package's `IntegrationTestCase` ships a `selfSignedCertPath()` helper that mints a fresh cert into a temp file and registers it for cleanup: + +```php +$pkey = openssl_pkey_new(['private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA]); +$csr = openssl_csr_new(['commonName' => 'localhost'], $pkey); +$x509 = openssl_csr_sign($csr, null, $pkey, 1); +openssl_x509_export($x509, $certPem); +openssl_pkey_export($pkey, $keyPem); + +$path = tempnam(sys_get_temp_dir(), 'initphp-socket-tls-') . '.pem'; +file_put_contents($path, $certPem . $keyPem); +``` + +## Plain-TCP coverage for `AbstractStreamClient` + +You can exercise the entire stream-client code path (connect, read, write, timeout, blocking, crypto-toggle) **without TLS** by talking to a `tcp://` stream server and using a tiny subclass of `AbstractStreamClient`: + +```php +final class PlainStreamClient extends AbstractStreamClient +{ + public function __construct(string $host, int $port, ?float $timeout = null) + { + parent::__construct($host, $port, Transport::TCP, $timeout); + } +} + +$server = stream_socket_server("tcp://127.0.0.1:{$port}"); +$client = new PlainStreamClient('127.0.0.1', $port); +$client->connect(); +$peer = stream_socket_accept($server, 1.0); + +$client->write('hello'); +self::assertSame('hello', fread($peer, 1024)); +``` + +No fork, no certs, no TLS handshake — just the stream-client I/O paths. + +## Coverage targets + +The CI workflow runs `composer test-coverage` with pcov on PHP 8.3 and uploads the Clover report to Codecov. The 2.0 release ships at: + +| Class | Lines | +|---|---| +| `Channel\StreamChannel` | 100% | +| `Channel\TcpChannel` | 100% | +| `Channel\UdpChannel` | 95% | +| `Client\AbstractClient` | 100% | +| `Client\AbstractStreamClient` | 98.5% | +| `Client\TCP` | 93.1% | +| `Client\TLS` / `SSL` | 100% | +| `Client\UDP` | 90% | +| `Enum\*` | 100% | +| `Server\AbstractServer` | 88.1% | +| `Server\AbstractStreamServer` | 86.3% | +| `Server\ServerConnection` | 100% | +| `Server\TCP` | ~85% | +| `Server\UDP` | ~85% | +| `Socket` (factory) | 88.9% | + +Overall: **≥ 90% line coverage**. The uncovered lines are mostly OS-call error paths (`socket_create` returning `false`, `socket_select` errors other than `EINTR`, …) that can't be triggered deterministically without mocking the socket extension. + +## See also + +- **[Event Loop Integration](Event-Loop-Integration.md)** — `tick()` is what makes deterministic tests possible. +- **[Recipe Custom Channel](Recipe-Custom-Channel.md)** — fakes that look like real channels. +- **[Connection and Channel](Connection-and-Channel.md)** — what a `ServerConnection` actually exposes to test code. diff --git a/docs/Transport-SSL.md b/docs/Transport-SSL.md new file mode 100644 index 0000000..70f4805 --- /dev/null +++ b/docs/Transport-SSL.md @@ -0,0 +1,77 @@ +# Transport — SSL + +The `ssl://` scheme variant of [Transport TLS](Transport-TLS.md). Functionally identical class layout; the only difference is the URL scheme passed to `stream_socket_server` / `stream_socket_client`, which affects PHP's default cipher negotiation. + +## When to choose `SSL` over `TLS` + +In nearly every situation — **don't**. Pick `Transport::TLS`. + +The `ssl://` scheme exists mostly for compatibility with legacy PHP code. Modern peers negotiate TLS 1.2 / 1.3 either way; the scheme just changes which cipher family PHP starts the negotiation in. + +The one common case where `Transport::SSL` is the natural fit is **implicit TLS** services with a long-established convention of being called over `ssl://` — e.g. SMTPS on port 465, IMAPS on 993, POP3S on 995. Either transport works there; `SSL` is what existing PHP examples in the wild use. + +## Server + +```php +use InitPHP\Socket\Socket; +use InitPHP\Socket\Enum\Transport; + +$server = Socket::server(Transport::SSL, '0.0.0.0', 8443, timeout: 5.0) + ->option('local_cert', __DIR__ . '/server.pem'); + +$server->listen(); +$server->live(function ($srv, $conn) { + $payload = $conn->read(); + if ($payload !== null) { + $conn->write("ssl-echo: {$payload}"); + } +}); +``` + +Every configuration knob, lifecycle method and exception type is identical to [Transport TLS](Transport-TLS.md) — read that page for the full reference. + +## Client + +```php +use InitPHP\Socket\Socket; +use InitPHP\Socket\Enum\Transport; + +$client = Socket::client(Transport::SSL, 'smtp.gmail.com', 465, timeout: 10.0) + ->option('verify_peer', false) + ->option('verify_peer_name', false); + +$client->connect(); +$client->write("EHLO [127.0.0.1]\r\n"); +echo $client->read(1024); +$client->disconnect(); +``` + +## Pinning a specific protocol version + +If you have a server that only speaks a specific version, pin it via `crypto()`: + +```php +use InitPHP\Socket\Enum\CryptoMethod; + +$client = Socket::client(Transport::SSL, 'legacy.example.com', 465); +$client->connect(); +$client->crypto(CryptoMethod::TLSv1_2); // upgrade or pin +``` + +For server-side, set the context option before `listen()`: + +```php +$server->crypto(CryptoMethod::TLSv1_2); +``` + +See [Enums](Enums.md) for every `CryptoMethod` case and how it maps to PHP's `STREAM_CRYPTO_METHOD_*` constants. + +## Why is the class still here? + +The interface symmetry is worth more than the deduplication. Code that selects a transport by configuration value (`tls` vs `ssl`) maps trivially onto the `Transport` enum. Removing one or the other would force every caller to special-case. + +## See also + +- **[Transport TLS](Transport-TLS.md)** — the canonical reference. Everything there applies to SSL. +- **[SSL Context Options](SSL-Context-Options.md)** — every key `option()` accepts. +- **[Recipe SMTP Client](Recipe-SMTP-Client.md)** — a runnable example using `Transport::SSL` against port 465. diff --git a/docs/Transport-TCP.md b/docs/Transport-TCP.md new file mode 100644 index 0000000..4160c75 --- /dev/null +++ b/docs/Transport-TCP.md @@ -0,0 +1,133 @@ +# Transport — TCP + +Stream-oriented, reliable, in-order delivery. The default and most-tested transport in the package, backed by `ext-sockets`. + +## When to choose TCP + +- The protocol expects an ordered byte stream (HTTP-like, line-based, custom framing on top of length-prefixed records). +- You need confirmation that bytes either arrived or the peer closed. +- Encryption is **not** required at this layer. (Use [Transport TLS](Transport-TLS.md) for that.) + +## Server + +```php +use InitPHP\Socket\Socket; +use InitPHP\Socket\Enum\{Transport, Domain}; + +$server = Socket::server(Transport::TCP, '127.0.0.1', 9000, Domain::V4); +$server->backlog(16); // optional, default 8 +$server->listen(); +$server->live(function ($srv, $conn) { + $payload = $conn->read(1024); + if ($payload !== null) { + $conn->write("echo: {$payload}"); + } +}); +``` + +Direct construction is also supported if you do not want the factory: + +```php +use InitPHP\Socket\Server\TCP as TcpServer; + +$server = (new TcpServer('127.0.0.1', 9000, Domain::V4))->backlog(16); +``` + +### Configuration + +| Method | Default | Effect | +|---|---|---| +| `backlog(int $n)` | `8` | OS listen backlog for pending connections waiting to be accepted. | + +`backlog()` is chainable and validates that `$n >= 1` (throws `SocketInvalidArgumentException` otherwise). + +### Inside `tick()` + +For TCP the per-iteration flow is: + +1. Build `[listenSocket, ...activeClients]` and hand it to `socket_select` with the supplied timeout. +2. For every readable resource: + - **Listening** → `socket_accept`, wrap in `TcpChannel`, set non-blocking, register. + - **Existing client** → `isAlive()` via `MSG_PEEK | MSG_DONTWAIT`. Dead → close + evict. Alive → invoke the callback. + +`socket_select` failures with `SOCKET_EINTR` are treated as benign (just retry on the next iteration). Other failures throw `SocketException`. + +## Client + +```php +use InitPHP\Socket\Socket; +use InitPHP\Socket\Enum\{Transport, Domain}; + +$client = Socket::client(Transport::TCP, '127.0.0.1', 9000, Domain::V4); +$client->connect(); + +$client->write("PING\r\n"); +echo $client->read(1024, PHP_NORMAL_READ); // line-oriented read + +$client->disconnect(); +``` + +### Read modes + +`read(int $length = 1024, int $type = PHP_BINARY_READ)` matches PHP's `socket_read`: + +| Constant | Behaviour | +|---|---| +| `PHP_BINARY_READ` (default) | Read up to `$length` raw bytes. | +| `PHP_NORMAL_READ` | Read until `\n` or `\r` is observed; the delimiter is **included** in the returned string. | + +## Address families + +```php +Socket::server(Transport::TCP, '127.0.0.1', 9000, Domain::V4); // IPv4 (default) +Socket::server(Transport::TCP, '::1', 9000, Domain::V6); // IPv6 +Socket::server(Transport::TCP, '/tmp/initphp.sock', 1, Domain::UNIX); // UDS +``` + +For `Domain::UNIX`, the constructor still demands `port >= 1`. The port is ignored by the kernel for UDS — pass any non-zero placeholder. A real-world UDS pattern is: + +```php +$server = Socket::server(Transport::TCP, '/var/run/myapp.sock', 1, Domain::UNIX); +$server->listen(); +chmod('/var/run/myapp.sock', 0660); +``` + +The `Domain` enum maps to `AF_INET` / `AF_INET6` / `AF_UNIX` internally; see [Enums](Enums.md). + +## Common gotchas + +### Half-closes + +TCP supports a half-close where the peer stops sending but still receives. The package treats any zero-byte `MSG_PEEK` as full close — there is no `shutdown()` exposed. If you need half-close semantics, call `socket_shutdown` on `$conn->getSocket()` yourself. + +### Backlog vs accept rate + +`backlog()` controls the kernel's pending-accept queue. Under burst load with a slow `tick()` cadence, raising the backlog buys you time. If clients see `ECONNREFUSED` under load, raise it. + +### `EINTR` from signal-heavy processes + +If you install signal handlers, `socket_select` will return `false` with `socket_last_error() === SOCKET_EINTR` whenever a signal fires during the call. The package treats this as benign and continues — no work is lost. + +## Exception flow + +| Error | Exception | +|---|---| +| `socket_create` fails | `SocketException` | +| `socket_bind` fails (port in use, perms, …) | `SocketException` | +| `socket_listen` fails | `SocketListenException` | +| `socket_accept` errors (non-EINTR) | `SocketConnectionException` | +| `socket_select` errors (non-EINTR) | `SocketException` | +| `socket_connect` fails | `SocketConnectionException` | +| `backlog($n < 1)` | `SocketInvalidArgumentException` | +| `connect()` twice on same client | `SocketException` | +| `listen()` twice on same server | `SocketException` | +| `tick()` before `listen()` | `SocketException` | + +Every one of these implements `SocketExceptionInterface` so a single catch can guard the whole transport. + +## See also + +- **[Server Lifecycle](Server-Lifecycle.md)** / **[Client Lifecycle](Client-Lifecycle.md)** — what the methods do across states. +- **[Connection and Channel](Connection-and-Channel.md)** — what `$conn->read()` actually calls. +- **[Recipe Echo Server](Recipe-Echo-Server.md)** — a runnable end-to-end example. +- **[Recipe Chat Server](Recipe-Chat-Server.md)** — `register()` + `broadcast()` patterns. diff --git a/docs/Transport-TLS.md b/docs/Transport-TLS.md new file mode 100644 index 0000000..c76885b --- /dev/null +++ b/docs/Transport-TLS.md @@ -0,0 +1,147 @@ +# Transport — TLS + +`tls://` stream wrapper with modern cipher selection. Use this for anything that talks current TLS (HTTPS, SMTPS, AMQPS, custom encrypted protocols). + +## Server + +```php +use InitPHP\Socket\Socket; +use InitPHP\Socket\Enum\Transport; + +$server = Socket::server(Transport::TLS, '0.0.0.0', 8443, timeout: 5.0) + ->option('local_cert', __DIR__ . '/server.pem') + ->option('verify_peer', false); + +$server->listen(); + +$server->live(function ($srv, $conn) { + $payload = $conn->read(); + if ($payload !== null) { + $conn->write("secure: {$payload}"); + } +}); +``` + +The TLS handshake happens **inside `stream_socket_accept`**. The package leaves the listening stream in blocking mode and uses the `$timeout` constructor argument as the handshake budget for each new client. `select()` still drives loop readiness — only the accept call itself is blocking. + +### Required options + +At minimum the server needs a certificate plus its private key. The simplest setup is a single PEM file with both: + +```php +$server->option('local_cert', '/etc/myapp/server.pem'); +``` + +If the key is encrypted, set `passphrase`. If the key is in a separate file, use `local_pk` for the private-key path. See [SSL Context Options](SSL-Context-Options.md) for the full list. + +### Fluent setters + +| Method | Default | Effect | +|---|---|---| +| `option(string $key, mixed $value)` | — | Set any SSL context option. | +| `timeout(float $seconds)` | `null` (uses `default_socket_timeout`) | Handshake budget for `stream_socket_accept`. | +| `blocking(bool $mode = true)` | `false` | Blocking mode of every newly accepted client stream. | +| `crypto(?CryptoMethod $method)` | `null` (URL scheme decides) | Pin a specific cipher family (`CryptoMethod::TLSv1_2`, …). `null` clears the override. | + +`crypto()` writes into the SSL context as `crypto_method` and applies to subsequent accepts. + +## Client + +```php +use InitPHP\Socket\Socket; +use InitPHP\Socket\Enum\Transport; + +$client = Socket::client(Transport::TLS, 'example.com', 443, timeout: 5.0) + ->option('verify_peer', true) + ->option('verify_peer_name', true) + ->option('cafile', '/etc/ssl/certs/ca-certificates.crt') + ->option('SNI_enabled', true); + +$client->connect(); + +$client->write("GET / HTTP/1.0\r\nHost: example.com\r\n\r\n"); +while (($chunk = $client->read(4096)) !== null) { + echo $chunk; +} +$client->disconnect(); +``` + +`connect()` runs `stream_socket_client` with the assembled context and verifies the certificate by default. The handshake completes inside `connect()`; once it returns, the stream is ready for application bytes. + +### Configuring after connect + +`timeout()` and `blocking()` are safe to call after `connect()` — they apply to the live stream: + +```php +$client->connect(); +$client->blocking(false); // make subsequent reads non-blocking +$client->timeout(2.0); // stream_set_timeout +``` + +`crypto()` toggles encryption on the live stream — useful for `STARTTLS`-style upgrades: + +```php +use InitPHP\Socket\Enum\CryptoMethod; + +$client = Socket::client(Transport::TLS, 'mail.example.com', 587); +$client->connect(); // unencrypted at this point if you use tcp:// — see note below +// EHLO, STARTTLS exchange ... +$client->crypto(CryptoMethod::TLSv1_2); // upgrade in place +``` + +> **Note:** `Transport::TLS` opens a `tls://` URL which negotiates TLS at connect time. For a true `STARTTLS` flow (start unencrypted, upgrade later) you would open a TCP connection and toggle crypto afterwards — see [Recipe SMTP Client](Recipe-SMTP-Client.md) for an implicit-TLS example, and the [PHP manual](https://www.php.net/manual/en/function.stream-socket-enable-crypto.php) for STARTTLS handling. + +`crypto(null)` disables crypto on a stream that previously had it enabled. + +### Calling `crypto()` before `connect()` + +The client has no stream to toggle yet, so `crypto()` throws `SocketException` if invoked before `connect()`. Configure the desired cipher family via `option('crypto_method', ...)` instead if you need to pin it at connect time. + +## Certificate generation (development only) + +For local testing you need a self-signed certificate. The fastest way is `openssl`: + +```bash +openssl req -x509 -newkey rsa:2048 -nodes -keyout key.pem -out cert.pem \ + -days 365 -subj '/CN=localhost' +cat cert.pem key.pem > server.pem +``` + +The package's test suite generates them in pure PHP via `openssl_csr_new` / `openssl_csr_sign` — see [Testing Strategy](Testing-Strategy.md) for a reusable snippet. For production, point `option('local_cert', ...)` at a real PEM bundle issued by your CA. + +## Common gotchas + +### Verifying the peer in production + +The development snippets disable `verify_peer` / `verify_peer_name` to accept self-signed certs. **Do not ship that**. In production, set `verify_peer => true` (default) and either `cafile` / `capath` for a custom trust store, or rely on the system CA bundle. + +### Server certificate hostname + +PHP's `verify_peer_name` matches the certificate's CN / SAN against the **host** argument you passed to `Socket::client(...)`. If you bind to `127.0.0.1` but the cert says `CN=example.com`, verification fails unless you turn off `verify_peer_name`. Prefer hostnames over IPs for TLS endpoints. + +### Handshake blocks accept + +`stream_socket_accept` blocks until the TLS handshake finishes. Under high fan-in, a slow handshake (or a hostile client that drips bytes) holds up the loop. For production-scale TLS terminate in a reverse proxy (HAProxy / nginx / Caddy) and run plain TCP behind it. + +### "no suitable signature algorithm" + +OpenSSL 3.x rejects older signature algorithms by default. If you have a legacy server, pin `CryptoMethod::TLSv1_0` or `TLSv1_1` via `crypto()` (and accept the security implications). + +## Exception flow + +| Error | Exception | +|---|---| +| `stream_socket_server` fails (bind / port in use) | `SocketListenException` | +| `stream_socket_client` fails (refused / handshake error) | `SocketConnectionException` | +| `stream_select` fails | `SocketException` | +| `listen()` twice | `SocketException` | +| `connect()` twice | `SocketException` | +| `crypto()` before `connect()` (client) | `SocketException` | +| `tick()` before `listen()` | `SocketException` | + +## See also + +- **[Transport SSL](Transport-SSL.md)** — the `ssl://` scheme variant. +- **[SSL Context Options](SSL-Context-Options.md)** — every key `option()` accepts. +- **[Recipe Self Signed TLS](Recipe-Self-Signed-TLS.md)** — generate a cert, bind, connect end-to-end. +- **[Recipe SMTP Client](Recipe-SMTP-Client.md)** — implicit-TLS over `Transport::SSL` against Gmail. diff --git a/docs/Transport-UDP.md b/docs/Transport-UDP.md new file mode 100644 index 0000000..29db585 --- /dev/null +++ b/docs/Transport-UDP.md @@ -0,0 +1,144 @@ +# Transport — UDP + +Datagram-oriented, connectionless. The package makes UDP look more connection-shaped without lying about the wire protocol. + +## When to choose UDP + +- You exchange small, idempotent messages (DNS queries, telemetry, NTP-style time sync). +- Loss is acceptable, or your protocol handles retransmits explicitly (QUIC-style, audio / video streaming). +- Latency matters more than reliability. + +UDP **never** retransmits, **never** orders, and the OS will silently drop datagrams if the receive buffer fills. + +## Server model — how "connection" works here + +A single listening socket fields datagrams from every peer. The package demultiplexes by source address: + +1. `tick()` does one `socket_recvfrom`, capturing the source `(host, port)`. +2. If that peer has a tracked `UdpChannel`, the channel receives the bytes via `feed()`. +3. Otherwise a fresh `UdpChannel` + `ServerConnection` is built for the peer and registered. +4. The callback fires with `($server, $connection)`. + +```php +use InitPHP\Socket\Socket; +use InitPHP\Socket\Enum\Transport; + +$server = Socket::server(Transport::UDP, '0.0.0.0', 9000); +$server->listen(); + +$server->live(function ($srv, $conn) { + $payload = $conn->read(65535); + if ($payload !== null) { + $conn->write("pong: {$payload}"); + } +}); +``` + +`$conn->read()` drains the channel's local buffer — it never goes back to the kernel. `$conn->write()` does a `socket_sendto` on the listening socket targeting the channel's bound peer. + +## Datagram sizes + +`UdpChannel::MAX_DATAGRAM = 65535` is the internal read buffer for `recvfrom`. The IPv4 ceiling for a UDP payload is **65 507 bytes** (UDP header + IP header + length field). For real-world reliability stay well under MTU (≈1472 bytes on Ethernet) to avoid IP fragmentation. + +## No backlog, no accept + +UDP has no listen queue and no `accept()`. `listen()` does `socket_create` + `socket_bind` only; the loop never calls accept. + +## Client + +```php +use InitPHP\Socket\Socket; +use InitPHP\Socket\Enum\Transport; + +$client = Socket::client(Transport::UDP, '127.0.0.1', 9000); +$client->connect(); + +$client->write('ping'); +echo $client->read(65535); + +$client->disconnect(); +``` + +`connect()` on a UDP client calls `socket_connect`, which on UDP just locks the local socket to a single peer at the kernel level. After that, you can `socket_send` / `socket_recv` as if it were a stream socket — that is exactly what `write()` / `read()` do internally. No datagram round-trip happens during `connect()`. + +### Flags + +Both `read()` and `write()` accept an optional `int $flags`: + +```php +$client->read(1024, MSG_PEEK); // inspect without consuming +$client->write('hello', MSG_DONTROUTE); +``` + +Recognised bitmask values mirror PHP's wrapper around `recv` / `send`: + +| Direction | Flags | +|---|---| +| `read()` | `MSG_OOB`, `MSG_PEEK`, `MSG_WAITALL`, `MSG_DONTWAIT` | +| `write()` | `MSG_OOB`, `MSG_EOR`, `MSG_EOF`, `MSG_DONTROUTE` | + +Leave `$flags` at the default `0` unless you specifically need one of these. + +## Liveness + +UDP has no connection state. `UdpChannel::isAlive()` returns `true` until you call `close()`. To evict silent peers, you need application-level TTL — track `lastSeen` per channel and call `$conn->close()` when it ages out: + +```php +$lastSeen = new SplObjectStorage(); +$server->live(function ($srv, $conn) use ($lastSeen) { + $payload = $conn->read(65535); + if ($payload !== null) { + $lastSeen[$conn] = microtime(true); + } + $now = microtime(true); + foreach ($srv->getClients() as $c) { + if (($lastSeen[$c] ?? 0) + 60.0 < $now) { + $c->close(); + } + } +}); +``` + +The next `tick()` after `close()` will evict the dead channel from `getClients()`. + +## Broadcast across known peers + +`broadcast()` iterates the channels the server has heard from. It is **not** the IP broadcast address — it is application-level fan-out. UDP has no peer-discovery, so a peer exists only after speaking first. + +```php +$server->broadcast('announce'); // every known peer +$server->broadcast('hello-admin', 'admin'); // by registered id +$server->broadcast('hi-vips', ['admin', 'vip']); +``` + +## Common gotchas + +### "Why did my datagram vanish?" + +- Receive buffer full → kernel dropped it. +- Peer wasn't listening yet → silent loss (no handshake). +- Payload bigger than MTU and `Don't Fragment` was set → ICMP error you may never see. + +UDP is silent in these cases by design. If you need confirmation, build acks into the protocol. + +### "Why are multiple datagrams concatenated in one `read()`?" + +They are not — but the package's `UdpChannel` buffer holds bytes from every datagram the kernel hands over between callbacks. If two datagrams arrive between two `tick()` calls, both are appended to the same internal buffer, and your next `$conn->read(1024)` returns up to 1024 bytes from the front. Either size your reads correctly or split datagrams via length-prefix framing in the application protocol. + +## Exception flow + +| Error | Exception | +|---|---| +| `socket_create` fails | `SocketException` | +| `socket_bind` fails | `SocketException` | +| `socket_select` errors (non-EINTR) | `SocketException` | +| `socket_connect` fails (UDP client) | `SocketConnectionException` | +| `listen()` twice | `SocketException` | +| `connect()` twice (client) | `SocketException` | +| `tick()` before `listen()` | `SocketException` | + +## See also + +- **[Server Lifecycle](Server-Lifecycle.md)** / **[Client Lifecycle](Client-Lifecycle.md)** +- **[Connection and Channel](Connection-and-Channel.md)** — `UdpChannel` specifics. +- **[Recipe Broadcast](Recipe-Broadcast.md)** — UDP fan-out pattern. diff --git a/docs/_Footer.md b/docs/_Footer.md new file mode 100644 index 0000000..9730445 --- /dev/null +++ b/docs/_Footer.md @@ -0,0 +1 @@ +**[initphp/socket](https://github.com/InitPHP/Socket)** · MIT · PHP 8.2+ · part of the [InitPHP](https://github.com/InitPHP) family · file issues at [InitPHP/Socket/issues](https://github.com/InitPHP/Socket/issues) diff --git a/docs/_Sidebar.md b/docs/_Sidebar.md new file mode 100644 index 0000000..4865b2e --- /dev/null +++ b/docs/_Sidebar.md @@ -0,0 +1,38 @@ +**[Home](Home.md)** + +**Getting started** +- [Installation](Installation.md) +- [Quick Start](Quick-Start.md) +- [Architecture](Architecture.md) + +**Transports** +- [TCP](Transport-TCP.md) +- [UDP](Transport-UDP.md) +- [TLS](Transport-TLS.md) +- [SSL](Transport-SSL.md) + +**Concepts** +- [Server Lifecycle](Server-Lifecycle.md) +- [Client Lifecycle](Client-Lifecycle.md) +- [Connection and Channel](Connection-and-Channel.md) +- [Event Loop Integration](Event-Loop-Integration.md) + +**Reference** +- [API Reference](API-Reference.md) +- [Enums](Enums.md) +- [Exceptions](Exceptions.md) +- [SSL Context Options](SSL-Context-Options.md) + +**Recipes** +- [Index](Recipes.md) +- [Echo Server](Recipe-Echo-Server.md) +- [Chat Server](Recipe-Chat-Server.md) +- [SMTP Client](Recipe-SMTP-Client.md) +- [Broadcast](Recipe-Broadcast.md) +- [Self-Signed TLS](Recipe-Self-Signed-TLS.md) +- [Custom Channel](Recipe-Custom-Channel.md) + +**Operational** +- [Testing Strategy](Testing-Strategy.md) +- [Migration Guide](Migration-Guide.md) +- [FAQ](FAQ.md) diff --git a/docs/architecture.md b/docs/architecture.md deleted file mode 100644 index a6ea82a..0000000 --- a/docs/architecture.md +++ /dev/null @@ -1,133 +0,0 @@ -# Architecture - -The 2.x line was designed around three goals: kill the shared-state bugs -of the 1.x release, isolate transport-specific I/O behind a strategy -interface, and stay friendly to host event loops. This page is the map -of how the pieces fit. - -## Layers at a glance - -``` -┌─────────────────────────────────────────────────────────────┐ -│ Socket factory │ -│ (Socket::server / Socket::client) │ -└─────────────────────────────────────────────────────────────┘ - │ - ┌─────────────────┴─────────────────┐ - ▼ ▼ -┌────────────────────┐ ┌────────────────────┐ -│ SocketServerInter │ │ SocketClientInter │ -│ face │ │ face │ -│ ─ AbstractServer │ │ ─ AbstractClient │ -│ ├─ TCP / UDP │ │ ├─ TCP / UDP │ -│ └─ AbstractStrea │ │ └─ AbstractStrea │ -│ mServer │ │ mClient │ -│ ├─ TLS │ │ ├─ TLS │ -│ └─ SSL │ │ └─ SSL │ -└────────────────────┘ └────────────────────┘ - │ │ - ▼ │ -┌────────────────────┐ │ -│ ServerConnection │ uses │ -│ (per accepted │◀─────────────────────┘ (clients hold the -│ client) │ resource directly) -└────────────────────┘ - │ - ▼ -┌────────────────────────────────────────┐ -│ ChannelInterface │ -│ ├─ TcpChannel (ext-sockets) │ -│ ├─ UdpChannel (ext-sockets, buffer) │ -│ └─ StreamChannel (ext-openssl streams) │ -└────────────────────────────────────────┘ -``` - -## Why `Channel`? - -A 1.x `ServerClient` carried a `switch ($type)` ladder in `push()`, -`read()`, `close()` and `isDisconnected()`. Adding a new transport meant -editing the class. The 2.x split moves transport-specific I/O into -dedicated `Channel` implementations: - -- **`TcpChannel`** uses `socket_recv` / `socket_write` and detects peer - close non-destructively with `MSG_PEEK | MSG_DONTWAIT`. -- **`StreamChannel`** uses `fread` / `fwrite` and asks `feof()` whether - the peer is gone — never consuming data to find out. -- **`UdpChannel`** binds an identity (`peerHost:peerPort`) to the - server's listening socket. The server routes inbound datagrams into - the channel's local buffer via `feed()`; reads drain the buffer. - Writes use `socket_sendto` directly. - -`ServerConnection` just holds an id and forwards calls to its channel. -That keeps the per-connection object honest about its scope — identity -plus delegation — and makes broadcasting / id mapping trivial to test -with a fake channel. - -## The server loop - -The accept/dispatch flow is broken into two layers: - -1. **`live(callable, float)`** — the long-running loop. It sets - `$running = true` and repeatedly calls `tick()` until `stop()` is - invoked. -2. **`tick(callable, float)`** — a single iteration. It runs the - transport-specific `select()`, accepts new connections, services - readable existing ones, and returns the number of events handled. - -The split is deliberate. `tick()` is the integration seam: drop the -package into a host event loop and call `tick(waitSeconds: 0)` whenever -your scheduler picks our server. Tests use the same seam to drive the -server deterministically without forking processes. - -## Why select-driven? - -The 1.x `live()` called blocking `socket_accept()` on every iteration, -so existing clients were ignored until a new one connected. The 2.x -loop builds a read set of `[listenSocket, ...activeClientSockets]`, -hands it to `socket_select` / `stream_select` with the caller-supplied -timeout, then services exactly the resources the kernel said are ready. - -Non-blocking accept is set after a `select()` reports a pending client, -not as a permanent property of the listening socket — `stream_socket_server` -behaves differently than `socket_create` here, and the stream-server -implementation keeps the listen socket blocking so `stream_socket_accept` -has room to complete the TLS handshake within its timeout. - -## Liveness, no data loss - -`isAlive()` never touches the application payload: - -- **TCP** — `socket_recv($sock, $tmp, 1, MSG_PEEK | MSG_DONTWAIT)`. A - zero return value means the peer closed; `EAGAIN`/`EWOULDBLOCK` means - alive-but-quiet. -- **Stream (TLS / SSL)** — `feof()` after confirming the resource is - still valid. -- **UDP** — an in-process `alive` flag; UDP has no connection state, - so dead peers are detected by application-level TTL. - -## Exceptions - -Every exception thrown by the package implements -`SocketExceptionInterface`, so callers can do: - -```php -try { - $server->listen(); -} catch (SocketExceptionInterface $e) { - // bind failed, listen failed, invalid argument — all caught here -} -``` - -The hierarchy: - -``` -SocketExceptionInterface -├─ SocketException (RuntimeException) -│ ├─ SocketConnectionException -│ └─ SocketListenException -└─ SocketInvalidArgumentException (InvalidArgumentException) -``` - -The split keeps the "your input is wrong" path on -`InvalidArgumentException` semantics while still being catchable -together with runtime failures via the marker interface. diff --git a/docs/client/ssl.md b/docs/client/ssl.md deleted file mode 100644 index 96bab8d..0000000 --- a/docs/client/ssl.md +++ /dev/null @@ -1,37 +0,0 @@ -# SSL client - -`InitPHP\Socket\Client\SSL` opens an `ssl://` stream. Functionally -identical to the [TLS client](./tls.md); the URL scheme just affects -PHP's default cipher negotiation. - -```php -use InitPHP\Socket\Socket; -use InitPHP\Socket\Enum\Transport; - -$client = Socket::client(Transport::SSL, 'smtp.gmail.com', 465, timeout: 10.0) - ->option('verify_peer', false) - ->option('verify_peer_name', false); - -$client->connect(); -$client->write("EHLO [127.0.0.1]\r\n"); -echo $client->read(1024); -$client->disconnect(); -``` - -Refer to the [TLS client guide](./tls.md) for the full option list and -error-handling notes — every helper translates directly. - -## When to pick `SSL` vs `TLS` - -Stick with `Transport::TLS` unless a specific server only accepts -`ssl://`. Modern peers negotiate TLS 1.2 / 1.3 either way; the -`ssl://` scheme is mostly useful for compatibility with legacy -endpoints. - -To force a specific protocol version, pin it via `crypto()`: - -```php -use InitPHP\Socket\Enum\CryptoMethod; - -$client->crypto(CryptoMethod::TLSv1_2); -``` diff --git a/docs/client/tcp.md b/docs/client/tcp.md deleted file mode 100644 index e1a3f57..0000000 --- a/docs/client/tcp.md +++ /dev/null @@ -1,56 +0,0 @@ -# TCP client - -A thin wrapper over `socket_create` + `socket_connect` for stream -sockets. - -## Quick reference - -```php -use InitPHP\Socket\Socket; -use InitPHP\Socket\Enum\{Transport, Domain}; - -$client = Socket::client(Transport::TCP, '127.0.0.1', 8080, Domain::V4); -$client->connect(); - -$client->write("PING\n"); -echo $client->read(1024); - -$client->disconnect(); -``` - -## Read modes - -`read(int $length = 1024, int $type = PHP_BINARY_READ)` accepts either -of the two PHP reading modes: - -| Constant | Behaviour | -| --- | --- | -| `PHP_BINARY_READ` (default) | Read up to `$length` raw bytes. | -| `PHP_NORMAL_READ` | Read until `\n` or `\r` is seen (line-oriented). | - -## Error handling - -`connect()` throws `SocketConnectionException` if the remote endpoint -refuses or the OS can't open the socket. `read()` / `write()` return -`null` instead of raising — wrap with your own retry logic if you -need it. - -```php -try { - $client->connect(); -} catch (\InitPHP\Socket\Exception\SocketConnectionException $e) { - // retry, fall back, log, ... -} -``` - -## UNIX domain sockets - -Pass `Domain::UNIX` and the filesystem path as the `host`: - -```php -$client = Socket::client(Transport::TCP, '/tmp/initphp.sock', 1, Domain::UNIX); -$client->connect(); -``` - -(The `port` argument is ignored for UDS, but must satisfy the `>0` -check — pass any placeholder.) diff --git a/docs/client/tls.md b/docs/client/tls.md deleted file mode 100644 index 472aff6..0000000 --- a/docs/client/tls.md +++ /dev/null @@ -1,66 +0,0 @@ -# TLS client - -A `tls://` stream client. Use this for anything talking modern TLS: -HTTPS, secure SMTP, AMQP, etc. - -## Quick reference - -```php -use InitPHP\Socket\Socket; -use InitPHP\Socket\Enum\Transport; - -$client = Socket::client(Transport::TLS, 'example.com', 443, timeout: 5.0); -$client->connect(); - -$client->write("GET / HTTP/1.0\r\nHost: example.com\r\n\r\n"); -while (($chunk = $client->read(4096)) !== null) { - echo $chunk; -} -$client->disconnect(); -``` - -## SSL context options - -`option(string $key, mixed $value)` is a passthrough for PHP's -[SSL context options](https://www.php.net/manual/en/context.ssl.php): - -```php -$client = Socket::client(Transport::TLS, 'example.com', 443) - ->option('verify_peer', true) - ->option('verify_peer_name', true) - ->option('cafile', '/etc/ssl/certs/ca-certificates.crt') - ->option('SNI_enabled', true); -``` - -For development against a self-signed server: - -```php -$client = Socket::client(Transport::TLS, '127.0.0.1', 8443) - ->option('verify_peer', false) - ->option('verify_peer_name', false) - ->option('allow_self_signed', true); -``` - -> **Never ship `verify_peer => false`.** Always configure trust correctly -> in production. The development flags exist for testing only. - -## Fluent helpers - -| Method | Purpose | -| --- | --- | -| `option(string $key, mixed $value)` | Set any SSL context option. | -| `timeout(float $seconds)` | Connect / handshake timeout. Applied to live streams too. | -| `blocking(bool $mode = true)` | Default `true` — set to `false` for non-blocking I/O. | -| `crypto(?CryptoMethod $method)` | Toggle / pin a specific cipher family after `connect()`. | - -## Error handling - -`connect()` throws `SocketConnectionException` when: - -- the TCP connect fails, -- the TLS handshake fails, -- or any underlying stream error is reported. - -Inspect the message for the `(errno): description` PHP returned. For -"peer's CN does not match" or "self signed certificate" errors, -re-check the `verify_*` / `cafile` options above. diff --git a/docs/client/udp.md b/docs/client/udp.md deleted file mode 100644 index f6ea0f3..0000000 --- a/docs/client/udp.md +++ /dev/null @@ -1,40 +0,0 @@ -# UDP client - -A datagram client. After `connect()`, the kernel locks the peer -address; `read()` / `write()` then behave like a stream socket and -talk only to that peer. - -## Quick reference - -```php -use InitPHP\Socket\Socket; -use InitPHP\Socket\Enum\Transport; - -$client = Socket::client(Transport::UDP, '127.0.0.1', 9000); -$client->connect(); - -$client->write('ping'); -echo $client->read(65535); - -$client->disconnect(); -``` - -## Flags - -Both `read()` and `write()` accept an optional `int $flags` argument: - -| Flag set | Sensible places | -| --- | --- | -| `MSG_OOB`, `MSG_PEEK`, `MSG_WAITALL`, `MSG_DONTWAIT` | `read()` | -| `MSG_OOB`, `MSG_EOR`, `MSG_EOF`, `MSG_DONTROUTE` | `write()` | - -Leave them at `0` unless you are sure you need them. - -## Caveats - -- **No retransmits.** A successful `write()` only proves the OS - accepted the packet for sending. Datagram loss is silent. -- **No connection state.** `disconnect()` only closes the local - socket; the peer has no way to learn the client is gone. -- **Packet size.** UDP over IPv4 maxes out at 65 507 bytes of payload. - Stay under MTU (≈1472 bytes on Ethernet) to avoid fragmentation. diff --git a/docs/cookbook/chat-server.md b/docs/cookbook/chat-server.md deleted file mode 100644 index 3a8970d..0000000 --- a/docs/cookbook/chat-server.md +++ /dev/null @@ -1,77 +0,0 @@ -# Cookbook — chat server - -A small TCP chat server that supports three commands: - -- `REGISTER ` — claim a name for the rest of the session. -- `SEND @ ` — direct message to a registered peer. -- anything else — broadcast to every connected client. - -```php -listen(); - -echo "Chat server listening on 127.0.0.1:8080\n"; - -$server->live(function (SocketServerInterface $srv, SocketConnectionInterface $conn) { - $input = $conn->read(4096); - if ($input === null) { - return; - } - $input = \trim($input); - if ($input === '') { - return; - } - - if (\in_array($input, ['quit', 'exit'], true)) { - $conn->write("Goodbye!\n"); - $conn->close(); - return; - } - - if (\preg_match('/^REGISTER\s+([\w-]{3,})$/i', $input, $m) === 1) { - $srv->register($m[1], $conn); - $conn->write("Registered as {$m[1]}\n"); - return; - } - - if (\preg_match('/^SEND\s+@([\w-]+)\s+(.+)$/i', $input, $m) === 1) { - $srv->broadcast("[{$conn->getId()} → {$m[1]}] {$m[2]}\n", $m[1]); - return; - } - - $srv->broadcast("[{$conn->getId()}] {$input}\n"); -}); -``` - -Try it from two terminals: - -```bash -# Terminal A -$ nc 127.0.0.1 8080 -REGISTER alice -Registered as alice - -# Terminal B -$ nc 127.0.0.1 8080 -REGISTER bob -Registered as bob -SEND @alice hey there -``` - -## Why it works - -- `register(id, conn)` records the mapping so `broadcast(message, id)` - can find the right channel. -- Until a client `REGISTER`s, `$conn->getId()` is `null` — the broadcast - line shows `null` which is fine for a demo. In a real product you - would refuse `SEND` until the sender is named. -- `$conn->close()` immediately tears the channel down; the next - `tick()` finds the socket dead and evicts it from `getClients()`. diff --git a/docs/cookbook/smtp-client.md b/docs/cookbook/smtp-client.md deleted file mode 100644 index cafff32..0000000 --- a/docs/cookbook/smtp-client.md +++ /dev/null @@ -1,71 +0,0 @@ -# Cookbook — SMTP client (raw) - -A minimal raw SMTP client that opens a TLS connection to Gmail and -performs the initial `EHLO` exchange. Useful as a smoke test that the -TLS client is configured correctly; **do not** ship this as a real -mailer — use `initphp/mailer` (or any battle-tested library) for that. - -```php -option('verify_peer', false) - ->option('verify_peer_name', false); - -$client->connect(); - -echo $client->read(1024); // 220 banner - -$client->write("EHLO localhost\r\n"); -echo $client->read(1024); // 250 capabilities - -$client->write("QUIT\r\n"); -echo $client->read(1024); - -$client->disconnect(); -``` - -Expected output (truncated): - -``` -220 smtp.gmail.com ESMTP … -250-smtp.gmail.com at your service, … -250-SIZE … -250-STARTTLS -250 SMTPUTF8 -221 2.0.0 closing connection -``` - -## Why these options - -- `Transport::SSL` because Gmail's `465` port serves implicit TLS - (the connection is encrypted from the first byte). For port `587` - you'd open a `TCP` connection first and upgrade it with `STARTTLS`. -- `verify_peer` is disabled here only for the demo. In a real client - you must verify the peer certificate (`option('cafile', ...)`). - -## Reading line-by-line - -SMTP is line-oriented. The simple `read(1024)` above takes whatever -chunk the OS hands over, which usually includes the full response. -For a robust client you would loop until the response code's final -line (`250 …`, not `250-…`): - -```php -function smtpRead($client): string -{ - $out = ''; - while (($chunk = $client->read(1024)) !== null) { - $out .= $chunk; - if (\preg_match('/^\d{3} [^\r\n]*\r?\n$/m', $chunk)) { - break; - } - } - return $out; -} -``` diff --git a/docs/getting-started.md b/docs/getting-started.md deleted file mode 100644 index 9a1a243..0000000 --- a/docs/getting-started.md +++ /dev/null @@ -1,88 +0,0 @@ -# Getting started - -`initphp/socket` is a thin layer on top of the PHP `sockets` extension and -the stream socket family. It gives you a transport-agnostic factory, a -non-blocking server loop and a small `Channel` abstraction so the same -mental model fits TCP, UDP, TLS and SSL. - -## Install - -```bash -composer require initphp/socket -``` - -You will also need `ext-sockets` (always) and `ext-openssl` (for TLS / SSL). - -## The five-minute tour - -```php -use InitPHP\Socket\Socket; -use InitPHP\Socket\Enum\Transport; -use InitPHP\Socket\Interfaces\{SocketServerInterface, SocketConnectionInterface}; - -// 1. Build a server. Nothing has happened on the network yet. -$server = Socket::server(Transport::TCP, '127.0.0.1', 9000); - -// 2. Bind and listen. -$server->listen(); - -// 3. Run the accept/dispatch loop. The callback is invoked whenever a -// connection has new inbound data. -$server->live(function (SocketServerInterface $srv, SocketConnectionInterface $conn) { - $payload = $conn->read(1024); - if ($payload === null) { - return; - } - $conn->write("got {$payload}"); -}); -``` - -The same pattern works for every transport — only the `Transport` case -changes: - -```php -Socket::server(Transport::TCP, '127.0.0.1', 9000); -Socket::server(Transport::UDP, '127.0.0.1', 9001); -Socket::server(Transport::TLS, '127.0.0.1', 9443, timeout: 5.0) - ->option('local_cert', __DIR__ . '/server.pem'); -Socket::server(Transport::SSL, '127.0.0.1', 9444, timeout: 5.0) - ->option('local_cert', __DIR__ . '/server.pem'); -``` - -## Clients mirror servers - -```php -$client = Socket::client(Transport::TCP, '127.0.0.1', 9000); -$client->connect(); -$client->write("hello\n"); -echo $client->read(1024); -$client->disconnect(); -``` - -## Lifecycle - -A server moves through three states: - -``` -constructed → listening → running → closed - listen() live() close() -``` - -A client is a two-step affair: - -``` -constructed → connected → closed - connect() disconnect() -``` - -Both servers and clients can be re-built; you cannot reuse a closed -instance. - -## Where to go next - -- [Architecture overview](./architecture.md) — how the pieces fit together. -- [Server guides](./server/tcp.md) — transport-by-transport details. -- [Client guides](./client/tcp.md) — same on the connect side. -- [Cookbook](./cookbook/chat-server.md) — runnable examples. -- [Migrating from 1.x](./migration-1.x-to-2.x.md) — if you're coming - from the previous major. diff --git a/docs/migration-1.x-to-2.x.md b/docs/migration-1.x-to-2.x.md deleted file mode 100644 index d89a2a2..0000000 --- a/docs/migration-1.x-to-2.x.md +++ /dev/null @@ -1,135 +0,0 @@ -# Migrating from 1.x to 2.x - -2.x is a clean break. The 1.x server loop had race conditions, lost -inbound data through its liveness check, and stored transport state on -a `static` property that leaked between instances. Fixing those needed -API changes, so 2.x ships with a new shape rather than a back-compat -shim. - -This guide walks the renames and behaviour changes you'll hit when -upgrading. The list is short — the public surface stays small. - -## Requirements - -| Aspect | 1.x | 2.x | -| --- | --- | --- | -| PHP | `>=7.4` | `^8.1` | -| Extensions | `ext-sockets` | `ext-sockets`, `ext-openssl` | -| Tested PHP versions | n/a (no CI) | 8.1, 8.2, 8.3 | - -## Factory - -```diff -- use InitPHP\Socket\Socket; -+ use InitPHP\Socket\Socket; -+ use InitPHP\Socket\Enum\Transport; - -- $server = Socket::server(Socket::TCP, '127.0.0.1', 8080); -+ $server = Socket::server(Transport::TCP, '127.0.0.1', 8080); -``` - -The integer constants (`Socket::TCP`, `Socket::UDP`, `Socket::TLS`, -`Socket::SSL`) are gone. The `Transport` enum takes their place. - -The `$argument` mystery parameter (whose meaning depended on transport) -is now two explicit named parameters: - -```diff -- Socket::server(Socket::TCP, '127.0.0.1', 8080, 'v4'); -+ Socket::server(Transport::TCP, '127.0.0.1', 8080, Domain::V4); - -- Socket::server(Socket::TLS, '127.0.0.1', 8443, 5.0); -+ Socket::server(Transport::TLS, '127.0.0.1', 8443, timeout: 5.0); -``` - -## Server method renames - -| 1.x | 2.x | Notes | -| --- | --- | --- | -| `connection()` | `listen()` | More accurate — it only binds + listens. Accept now happens inside `live()` / `tick()`. | -| `disconnect()` | `close()` | Tears down every client and the listening socket. | -| `live(callable $cb, int $usleep = 100000)` | `live(callable $cb, float $idleSeconds = 0.05)` | Same idea, now expressed in seconds. | -| `wait(int\|float $seconds)` | `wait(float $seconds)` | Sub-second precision via a single float. | -| `clientRegister($id, $conn)` | `register($id, $conn)` | Now part of the interface. | -| `broadcast($message, $clients = null)` | `broadcast(string $message, int\|string\|array\|null $ids = null)` | Always returns `bool`. Per-id targeting unchanged. | - -New on `SocketServerInterface`: - -- `tick(callable $cb, float $waitSeconds = 0.0): int` — single-iteration - accept/dispatch step. Use this to embed the server in your own - event loop or to drive it deterministically in tests. -- `stop(): void` — cooperatively exit the `live()` loop. -- `isRunning(): bool` — exposes the loop flag. - -## ServerClient → ServerConnection - -The per-accepted-connection class has been renamed and rebuilt: - -| 1.x: `Server\ServerClient` | 2.x: `Server\ServerConnection` | -| --- | --- | -| `push(string $msg)` | `write(string $data): ?int` | -| `read(int $len, ?int $type = null)` | `read(int $len = 1024): ?string` | -| `close(): bool` | `close(): bool` | -| `isDisconnected(): bool` (consumed data!) | `isAlive(): bool` (non-destructive) | -| `getSocket()` returns mixed | `getSocket(): mixed`, plus `getChannel(): ChannelInterface` | -| `__setSocket()` magic | gone — channels are constructed normally | -| `static $credentials` shared state | gone — every connection owns its own `Channel` | - -The most important behavioural change: **`isAlive()` does not read -data off the wire.** If you were depending on `isDisconnected()` to -both check liveness and consume the next line, you need to call -`read()` explicitly. - -## Client method renames - -| 1.x | 2.x | -| --- | --- | -| `connection()` | `connect()` | -| `disconnect()` | `disconnect()` (unchanged) | -| `read()` / `write()` | `read()` / `write()` (unchanged shape; return `null` instead of `false`) | - -## Exceptions - -All exceptions now implement a common `SocketExceptionInterface`. The -behavioural changes: - -- `SocketException` now extends `\RuntimeException` (was `\Exception`). -- `SocketConnectionException` and `SocketListenException` extend - `SocketException` (were `\Exception`). -- A single catch covers the package: - -```diff -- try { /* ... */ } catch (\InitPHP\Socket\Exception\SocketException $e) { /* ... */ } -+ try { /* ... */ } catch (\InitPHP\Socket\Exception\SocketExceptionInterface $e) { /* ... */ } -``` - -## Removed traits and base classes - -The `Common/` namespace is gone. If you were extending or composing -`BaseClient`, `BaseServer`, `BaseCommon`, `ServerTrait`, -`StreamClientTrait` or `StreamServerTrait`, switch to the new -abstracts: - -| 1.x | 2.x | -| --- | --- | -| `Common\BaseClient` | `Client\AbstractClient` | -| `Common\BaseServer` | `Server\AbstractServer` | -| `Common\StreamClientTrait` | `Client\AbstractStreamClient` | -| `Common\StreamServerTrait` | `Server\AbstractStreamServer` | -| `Common\BaseCommon` / `Common\ServerTrait` | merged into the abstracts | - -## Quick migration checklist - -1. Bump `php` to `^8.1` in your project's `composer.json`. -2. Replace every `Socket::TCP` / `Socket::UDP` / `Socket::TLS` / - `Socket::SSL` reference with the `Transport` enum case. -3. Replace `connection()` → `listen()` / `connect()`. -4. Replace `disconnect()` → `close()` on servers (clients keep it). -5. Rename `ServerClient` references to `ServerConnection` and - `push()` to `write()`. -6. Audit every call to the old `isDisconnected()` — replace with - `isAlive()` and read data explicitly. -7. If you have your own subclasses, point them at the new abstract - parents under `Server/` / `Client/`. -8. Catch `SocketExceptionInterface` instead of (or in addition to) - `SocketException`. diff --git a/docs/server/ssl.md b/docs/server/ssl.md deleted file mode 100644 index 227b8f2..0000000 --- a/docs/server/ssl.md +++ /dev/null @@ -1,35 +0,0 @@ -# SSL server - -`InitPHP\Socket\Server\SSL` is the `ssl://` scheme counterpart of -[TLS](./tls.md). The class is functionally identical — the only -difference is the URL scheme passed to `stream_socket_server`, which -affects the default ciphers PHP selects. - -```php -use InitPHP\Socket\Socket; -use InitPHP\Socket\Enum\Transport; - -$server = Socket::server(Transport::SSL, '127.0.0.1', 8443, timeout: 5.0) - ->option('local_cert', __DIR__ . '/server.pem'); - -$server->listen(); -``` - -Refer to the [TLS server guide](./tls.md) for the full option list, -handshake notes and certificate setup; everything translates directly. - -## When to pick `SSL` vs `TLS` - -Prefer `Transport::TLS` unless you specifically need the legacy SSLv23 -/ SSLv2 / SSLv3 fallback selection. Modern peers negotiate TLS 1.2 / -1.3 either way; the `ssl://` scheme exists for compatibility with old -PHP code and rarely gives you anything new. - -If you need a specific protocol version, set it explicitly with -`crypto()`: - -```php -use InitPHP\Socket\Enum\CryptoMethod; - -$server->crypto(CryptoMethod::TLSv1_2); -``` diff --git a/docs/server/tcp.md b/docs/server/tcp.md deleted file mode 100644 index 34bb16b..0000000 --- a/docs/server/tcp.md +++ /dev/null @@ -1,112 +0,0 @@ -# TCP server - -Backed by the `sockets` extension (`socket_create` / `socket_listen` / -`socket_accept`). Suitable for any stream-oriented binary or text -protocol. - -## Quick reference - -```php -use InitPHP\Socket\Socket; -use InitPHP\Socket\Enum\{Transport, Domain}; - -$server = Socket::server( - Transport::TCP, - '127.0.0.1', - 8080, - domain: Domain::V4, // V4 (default), V6 or UNIX -); - -$server->listen(); -$server->live(function ($srv, $conn) { - $payload = $conn->read(1024); - if ($payload !== null) { - $conn->write("ack:{$payload}"); - } -}); -``` - -## Options - -| Method | Default | Notes | -| --- | --- | --- | -| `backlog(int $n)` | `8` | OS listen backlog for unaccepted connections. | - -## Domain selection - -| `Domain` case | Address family | -| --- | --- | -| `V4` | `AF_INET` (default) | -| `V6` | `AF_INET6` | -| `UNIX` | `AF_UNIX` (UDS path goes in the `host` argument) | - -UDS example: - -```php -$server = Socket::server(Transport::TCP, '/tmp/initphp.sock', 0, Domain::UNIX); -``` - -> **Note:** for `Domain::UNIX`, the `port` argument is ignored by the -> kernel but still has to satisfy the constructor's `>0` check; pass -> any non-zero placeholder (or use a real port if you ever expose the -> service via TCP too). - -## Lifecycle in code - -```php -$server = Socket::server(Transport::TCP, '127.0.0.1', 8080); - -// throws SocketListenException if bind/listen fails -$server->listen(); - -try { - $server->live(function ($srv, $conn) { - // ... - }); -} finally { - $server->close(); // tears down every client + the listen socket -} -``` - -## Targeted broadcasting - -```php -$server->live(function ($srv, $conn) { - $payload = $conn->read(); - if ($payload === null) return; - - if (\preg_match('/^REGISTER\s+(.+)$/', $payload, $m)) { - $srv->register($m[1], $conn); - return; - } - if (\preg_match('/^DM\s+(\S+)\s+(.+)$/', $payload, $m)) { - $srv->broadcast($m[2], $m[1]); // single id - return; - } - $srv->broadcast($payload); // every client -}); -``` - -`broadcast()` accepts: - -- `null` — every alive client -- `int|string` — the connection previously registered under that id -- `int[]|string[]` — multiple ids at once - -## Driving the loop yourself - -`live()` is just `while (running) tick()`. If you have your own loop, -use `tick()` directly: - -```php -$server->listen(); -while ($app->isRunning()) { - $events = $server->tick(function ($srv, $conn) { - /* ... */ - }, waitSeconds: 0.0); - - if ($events === 0) { - $app->yieldOnce(); - } -} -``` diff --git a/docs/server/tls.md b/docs/server/tls.md deleted file mode 100644 index 13f7823..0000000 --- a/docs/server/tls.md +++ /dev/null @@ -1,78 +0,0 @@ -# TLS server - -TLS servers wrap `stream_socket_server` with an `ssl://` context (`tls` -scheme). Both the listen and the per-client handshake go through PHP -stream encryption. - -## Quick reference - -```php -use InitPHP\Socket\Socket; -use InitPHP\Socket\Enum\Transport; - -$server = Socket::server(Transport::TLS, '127.0.0.1', 8443, timeout: 5.0) - ->option('local_cert', __DIR__ . '/server.pem') // cert + private key - ->option('verify_peer', false) - ->option('allow_self_signed', true); - -$server->listen(); -$server->live(function ($srv, $conn) { - $payload = $conn->read(); - if ($payload !== null) { - $conn->write("secure: {$payload}"); - } -}); -``` - -## Required SSL context options - -At minimum the server needs `local_cert` (a PEM bundle of the -certificate and its private key). Every option you can pass to PHP's -SSL context is also available here — see the -[PHP manual](https://www.php.net/manual/en/context.ssl.php). - -Common keys: - -| Option | Why you might set it | -| --- | --- | -| `local_cert` | Path to a PEM file with the server certificate (and optionally the private key). | -| `local_pk` | Path to the private key if it lives in a separate file. | -| `passphrase` | Passphrase protecting the private key. | -| `cafile` / `capath` | Trusted CA bundle if you ask clients to authenticate. | -| `verify_peer` | Default `true` — drop the connection if the peer cert can't be verified. | -| `verify_peer_name` | Default `true` — match the certificate CN/SAN against the peer name. | -| `allow_self_signed` | Useful in dev; **do not** ship it. | - -## Fluent helpers - -| Method | Purpose | -| --- | --- | -| `option(string $key, mixed $value)` | Set any SSL context option. | -| `timeout(float $seconds)` | Default socket / handshake timeout. | -| `blocking(bool $mode = true)` | Whether accepted client streams stay blocking. Default `false`. | -| `crypto(?CryptoMethod $method)` | Pin a specific cipher family (`CryptoMethod::TLSv1_2`, …) or `null` to defer to the URL scheme. | - -## Generating a self-signed certificate for local testing - -```bash -openssl req -x509 -newkey rsa:2048 -nodes -keyout key.pem -out cert.pem \ - -days 365 -subj '/CN=localhost' -cat cert.pem key.pem > server.pem -``` - -Point `option('local_cert', ...)` at the resulting `server.pem`. - -## Caveats - -- **Handshake happens during accept.** `live()` / `tick()` may briefly - block during the TLS exchange of a new connection. For loopback - this is in the low milliseconds; for high-fan-in remote workloads, - consider terminating TLS in a reverse proxy. -- **The listening stream stays in blocking mode** so the handshake has - room to complete inside `stream_socket_accept`'s timeout. `select()` - still drives readiness — the loop will not idle on a blocking - accept call. -- **Verify the peer in production.** The defaults assume you mean it - when you say "verify_peer=false". For real deployments, point - `cafile` at the trust anchor and leave `verify_peer` / `verify_peer_name` - on. diff --git a/docs/server/udp.md b/docs/server/udp.md deleted file mode 100644 index 7b3526a..0000000 --- a/docs/server/udp.md +++ /dev/null @@ -1,57 +0,0 @@ -# UDP server - -UDP is connectionless: a single listening socket fields datagrams from -every peer. `initphp/socket` makes the abstraction look more -connection-shaped without lying about it. - -## What "connection" means for UDP here - -Each unique `peerHost:peerPort` seen on the wire gets its own -`UdpChannel` and `ServerConnection`. The server demultiplexes inbound -datagrams into the right channel via the channel's internal buffer -(`feed()`), so your callback can call `$conn->read()` and get only the -datagrams that came from that peer. - -`broadcast()` sends to every tracked peer. There is **no peer -discovery** — a peer exists only after it has spoken to the server. - -## Quick reference - -```php -use InitPHP\Socket\Socket; -use InitPHP\Socket\Enum\Transport; - -$server = Socket::server(Transport::UDP, '0.0.0.0', 9000); -$server->listen(); - -$server->live(function ($srv, $conn) { - $payload = $conn->read(65535); - if ($payload !== null) { - $conn->write("pong: {$payload}"); - } -}); -``` - -## Datagram sizing - -The internal read size is `UdpChannel::MAX_DATAGRAM = 65535`. The -practical upper bound for a UDP payload over IPv4 is **65 507 bytes**; -keep messages comfortably under MTU (≈1472 bytes on Ethernet) if you -care about avoiding fragmentation. - -## No backlog, no listen() call - -UDP doesn't have a listen queue, so `backlog()` does not exist. The -`listen()` method only performs `socket_create` + `socket_bind` for -this transport. - -## Caveats - -- **No reliability, no ordering.** That's UDP. If your protocol needs - retransmits, build them on top. -- **Peer eviction is your job.** The server never removes a UDP - connection on its own — you decide when a silent peer has gone away - (heartbeat, TTL, etc.) and call `$conn->close()`. -- **No `isAlive()` truth.** `UdpChannel::isAlive()` simply tracks - whether you have closed it; the protocol cannot tell you the peer is - gone.