PHPackages                             initphp/socket - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [DevOps &amp; Deployment](/categories/devops)
4. /
5. initphp/socket

ActiveLibrary[DevOps &amp; Deployment](/categories/devops)

initphp/socket
==============

Lightweight TCP, UDP, TLS and SSL socket server/client toolkit for PHP 8.1+.

2.0.0(1mo ago)114.6k↓55.2%[1 PRs](https://github.com/InitPHP/Socket/pulls)MITPHPPHP ^8.1CI passing

Since Mar 18Pushed 3w ago2 watchersCompare

[ Source](https://github.com/InitPHP/Socket)[ Packagist](https://packagist.org/packages/initphp/socket)[ RSS](/packages/initphp-socket/feed)WikiDiscussions main Synced yesterday

READMEChangelog (3)Dependencies (3)Versions (12)Used By (0)

initphp/socket
==============

[](#initphpsocket)

[![Latest Stable Version](https://camo.githubusercontent.com/3916db0bd7876a5489109c7a928cea3d67b4bb2c4a403358e040360c4c619e99/68747470733a2f2f706f7365722e707567782e6f72672f696e69747068702f736f636b65742f76)](https://packagist.org/packages/initphp/socket)[![Total Downloads](https://camo.githubusercontent.com/17363df82149758fbad214e897e143974fff6affb14d4cfc7597c78637f1b36c/68747470733a2f2f706f7365722e707567782e6f72672f696e69747068702f736f636b65742f646f776e6c6f616473)](https://packagist.org/packages/initphp/socket)[![License](https://camo.githubusercontent.com/70d2619b3f29769043df2344299347fab65998e7d1ea70b0df824c893314057e/68747470733a2f2f706f7365722e707567782e6f72672f696e69747068702f736f636b65742f6c6963656e7365)](https://packagist.org/packages/initphp/socket)[![PHP Version Require](https://camo.githubusercontent.com/2200d4c98a2644f8933b71cd5af00f801b9fcd87747f05d0090686c14a0646a5/68747470733a2f2f706f7365722e707567782e6f72672f696e69747068702f736f636b65742f726571756972652f706870)](https://packagist.org/packages/initphp/socket)[![CI](https://github.com/InitPHP/Socket/actions/workflows/ci.yml/badge.svg)](https://github.com/InitPHP/Socket/actions/workflows/ci.yml)

A lightweight TCP, UDP, TLS and SSL socket toolkit for PHP 8.1+. Both server and client sides share a clean, typed API built around enums and a small `Channel` strategy so each transport plugs in without `switch` ladders.

```
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) {
    $message = $conn->read(1024);
    $conn->write("echo: {$message}");
});
```

Requirements
------------

[](#requirements)

- PHP **8.1+**
- ext-sockets
- ext-openssl (TLS / SSL)
- ext-pcntl (only for the integration test suite)

Installation
------------

[](#installation)

```
composer require initphp/socket
```

Features
--------

[](#features)

- **TCP, UDP, TLS, SSL** — one factory, one interface per side.
- **Non-blocking, select-driven server loop** — `live()` runs forever, or drive the loop yourself one iteration at a time with `tick()` (great for embedding into your own event loop or for deterministic tests).
- **First-class enums** — `Transport`, `Domain` and `CryptoMethod` replace magic strings and integer flags.
- **Strategy-based channels** — `TcpChannel`, `UdpChannel` and `StreamChannel` isolate the transport-specific I/O. No static state shared between server instances.
- **Coherent exception hierarchy** — every exception implements `SocketExceptionInterface`, so a single catch covers the package.
- **Typed everywhere** — PHP 8.1 enums, readonly promoted properties, full `declare(strict_types=1)` coverage.
- **No silent data loss** — liveness checks never consume data from the wire.

Quick start
-----------

[](#quick-start)

### TCP echo server

[](#tcp-echo-server)

```
use InitPHP\Socket\Socket;
use InitPHP\Socket\Enum\Transport;
use InitPHP\Socket\Interfaces\{SocketServerInterface, SocketConnectionInterface};

$server = Socket::server(Transport::TCP, '127.0.0.1', 8080);
$server->listen();

$server->live(function (SocketServerInterface $srv, SocketConnectionInterface $conn) {
    $message = $conn->read(1024);
    if ($message === null) {
        return;
    }
    if ($message === 'quit') {
        $conn->write("bye\n");
        $conn->close();
        return;
    }
    $conn->write("echo: {$message}");
});
```

### TCP client

[](#tcp-client)

```
use InitPHP\Socket\Socket;
use InitPHP\Socket\Enum\Transport;

$client = Socket::client(Transport::TCP, '127.0.0.1', 8080);
$client->connect();

$client->write("hello\n");
echo $client->read(1024);

$client->disconnect();
```

### TLS server (chat-style with named clients)

[](#tls-server-chat-style-with-named-clients)

```
use InitPHP\Socket\Socket;
use InitPHP\Socket\Enum\Transport;
use InitPHP\Socket\Interfaces\{SocketServerInterface, SocketConnectionInterface};

$server = Socket::server(Transport::TLS, '127.0.0.1', 8443, timeout: 5.0)
    ->option('local_cert', __DIR__ . '/server.pem')
    ->option('allow_self_signed', true);

$server->listen();

$server->live(function (SocketServerInterface $srv, SocketConnectionInterface $conn) {
    $input = $conn->read();
    if ($input === null) {
        return;
    }
    if (\preg_match('/^REGISTER\s+([\w-]{3,})$/i', $input, $m) === 1) {
        $srv->register($m[1], $conn);
        $conn->write("Welcome, {$m[1]}\n");
        return;
    }
    if (\preg_match('/^SEND\s+@([\w-]+)\s+(.*)$/i', $input, $m) === 1) {
        $srv->broadcast($m[2], $m[1]);
        return;
    }
    $srv->broadcast(\trim($input));
});
```

### SSL client (talking to Gmail SMTP)

[](#ssl-client-talking-to-gmail-smtp)

```
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();
```

API surface
-----------

[](#api-surface)

### Factory — `InitPHP\Socket\Socket`

[](#factory--initphpsocketsocket)

```
Socket::server(
    Transport $transport,
    string $host,
    int $port,
    ?Domain $domain = null,   // Defaults to Domain::V4 for TCP/UDP. Ignored for TLS/SSL.
    ?float $timeout = null,   // Connect/handshake timeout for TLS/SSL.
): SocketServerInterface;

Socket::client(
    Transport $transport,
    string $host,
    int $port,
    ?Domain $domain = null,
    ?float $timeout = null,
): SocketClientInterface;
```

### Servers — `InitPHP\Socket\Interfaces\SocketServerInterface`

[](#servers--initphpsocketinterfacessocketserverinterface)

MethodPurpose`listen(): static`Bind and start listening. Does **not** accept clients.`live(callable $cb, float $idle = 0.05): void`Run the accept/dispatch loop until `stop()` is called.`tick(callable $cb, float $wait = 0.0): int`One iteration of the loop. Returns events processed.`stop(): void`Cooperatively exit the loop started by `live()`.`close(): bool`Tear everything down (every client + the listening socket).`broadcast(string $msg, int|string|array|null $ids = null): bool`Send to all clients or a targeted subset.`register(int|string $id, SocketConnectionInterface $conn): bool`Attach an addressable id to a connection.`getClients(): array`Map of `id`AbstractStreamServer` (TLS / SSL) additionally exposes:

```
$server->option(string $key, mixed $value): static  // SSL stream context option
$server->timeout(float $seconds): static
$server->blocking(bool $mode = true): static
$server->crypto(?CryptoMethod $method): static
```

### Clients — `InitPHP\Socket\Interfaces\SocketClientInterface`

[](#clients--initphpsocketinterfacessocketclientinterface)

MethodPurpose`connect(): static`Open the connection.`disconnect(): bool`Close the connection. Idempotent.`read(int $len = 1024): ?string`Receive up to `$len` bytes. Returns `null` on no data / failure.`write(string $data): ?int`Send `$data`. Returns the number of bytes written, or `null` on failure.`AbstractStreamClient` (TLS / SSL) adds `option()`, `timeout()`, `blocking()`and `crypto()` — same shape as the server side.

### Enums

[](#enums)

```
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

[](#exceptions)

Every package exception implements `SocketExceptionInterface`, so a single `catch (SocketExceptionInterface $e)` covers them all.

```
SocketExceptionInterface
├── SocketException                 (extends \RuntimeException)
│   ├── SocketConnectionException
│   └── SocketListenException
└── SocketInvalidArgumentException  (extends \InvalidArgumentException)

```

Embedding into your own event loop
----------------------------------

[](#embedding-into-your-own-event-loop)

If you already run an event loop (ReactPHP, Amp, Swoole-bridge, etc.), do not call `live()` — invoke `tick()` from your loop and let the host decide when to yield:

```
$server->listen();

while ($yourEventLoop->running()) {
    $events = $server->tick(function ($srv, $conn) { /* ... */ }, waitSeconds: 0.0);
    if ($events === 0) {
        $yourEventLoop->yield();
    }
}
```

Documentation
-------------

[](#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)

Development
-----------

[](#development)

```
composer install
composer test       # PHPUnit (unit + integration)
composer stan       # PHPStan level 8
composer cs-check   # PHP-CS-Fixer dry-run
composer cs-fix     # Apply style fixes
composer qa         # All of the above
```

CI runs the full QA pipeline on PHP 8.1, 8.2 and 8.3.

Contributing
------------

[](#contributing)

Issues, ideas and pull requests are welcome. Please read the [org-wide contributing guide](https://github.com/InitPHP/.github/blob/main/CONTRIBUTING.md)before opening a PR.

Security issues should be reported privately — see [SECURITY.md](https://github.com/InitPHP/.github/blob/main/SECURITY.md).

Credits
-------

[](#credits)

- [Muhammet ŞAFAK](https://www.muhammetsafak.com.tr) — ``

License
-------

[](#license)

Released under the [MIT License](./LICENSE).

###  Health Score

53

—

FairBetter than 96% of packages

Maintenance94

Actively maintained with recent releases

Popularity28

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity64

Established project with proven stability

 Bus Factor1

Top contributor holds 75% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~255 days

Recently: every ~135 days

Total

7

Last Release

39d ago

Major Versions

1.x-dev → 2.x-dev2026-05-24

PHP version history (2 changes)1.0PHP &gt;=7.4

2.x-devPHP ^8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/4b6b34f3ac8938d8ee52ba3bd260680855dc5715c7b2929d9380de30d15a67dd?d=identicon)[muhammetsafak](/maintainers/muhammetsafak)

---

Top Contributors

[![muhammetsafak](https://avatars.githubusercontent.com/u/104234499?v=4)](https://github.com/muhammetsafak "muhammetsafak (12 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (4 commits)")

---

Tags

event-loopinitphpnetwork-programmingnetworkingphpphp8php81socket-clientsocket-serversocketssslstream-sockettcptlsudpstreamclientservertcptlsSocketsslnetworkingudpinitphp

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/initphp-socket/health.svg)

```
[![Health](https://phpackages.com/badges/initphp-socket/health.svg)](https://phpackages.com/packages/initphp-socket)
```

###  Alternatives

[clue/socket-raw

Simple and lightweight OOP wrapper for PHP's low-level sockets extension (ext-sockets).

35312.1M50](/packages/clue-socket-raw)[voryx/thruway

Thruway WAMP router core

6751.0M17](/packages/voryx-thruway)[react/datagram

Event-driven UDP datagram socket client and server for ReactPHP

99868.6k45](/packages/react-datagram)[thiagof/laravelrpc

JsonRPC Client/Server services for Laravel 5

337.6k](/packages/thiagof-laravelrpc)[pikart/goip

Goip server and client

318.3k](/packages/pikart-goip)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
