PHPackages                             matasarei/phptcp - 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. [HTTP &amp; Networking](/categories/http)
4. /
5. matasarei/phptcp

ActiveLibrary[HTTP &amp; Networking](/categories/http)

matasarei/phptcp
================

A TCP client for PHP

1.2.0(3w ago)1151MITPHPPHP &gt;=7.4CI passing

Since Sep 1Pushed 3w ago2 watchersCompare

[ Source](https://github.com/matasarei/phptcp)[ Packagist](https://packagist.org/packages/matasarei/phptcp)[ RSS](/packages/matasarei-phptcp/feed)WikiDiscussions main Synced 1w ago

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

PhpTcp
======

[](#phptcp)

[![Tests](https://github.com/matasarei/phptcp/actions/workflows/tests.yml/badge.svg)](https://github.com/matasarei/phptcp/actions/workflows/tests.yml)[![PHP Version Require](https://camo.githubusercontent.com/0903ffbed9180feed8190561720df32cc4e52947f2fdfafed0ca413cd4f51f28/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646570656e64656e63792d762f6d61746173617265692f7068707463702f7068702e737667)](composer.json)[![License](https://camo.githubusercontent.com/5e26968d1e2e0dbec338ba200b129eb19d1c641149cfc54cd240b55c10d590c6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6d61746173617265692f7068707463702e737667)](LICENSE)

A lightweight TCP client for PHP with no runtime dependencies beyond a PSR-3 logger interface. It wraps PHP's native stream functions in a small, testable API: pluggable socket transports, configurable timeouts, optional delimiter-based response framing and PSR-3 logging.

Well suited for simple text-based request/response protocols — line-delimited JSON, JSON-RPC over TCP, custom device or legacy service protocols, and similar.

Features
--------

[](#features)

- Simple connect / request / disconnect API over plain TCP
- Two built-in transports — `StreamSocket` (`stream_socket_client`) and `FSocket` (`fsockopen`) — plus a one-method `SocketInterface` for custom transports
- Optional end-of-response delimiter for line-based protocols (see [Response framing](#response-framing))
- Detects broken streams and connections closed by the peer; completes partial writes
- Configurable connection, request and read timeouts
- PSR-3 (`psr/log` v1, v2 or v3) logger support for debugging

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

[](#requirements)

- PHP 7.4 or newer

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

[](#installation)

```
composer require matasarei/phptcp
```

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

[](#quick-start)

```
use Matasar\PhpTcp\Client;
use Matasar\PhpTcp\Request;
use Matasar\PhpTcp\Socket\StreamSocket;

$client = new Client('ip_or_hostname', 8888, new StreamSocket());
$client->connect();

$response = $client->request(new Request('request data'));
$client->disconnect();

var_dump($response->getData());
```

`Request` accepts an optional per-request timeout in seconds (default 30):

```
$request = new Request('request data', 5);
```

Socket transports
-----------------

[](#socket-transports)

The library includes two transports: `StreamSocket` and `FSocket`. The difference is `stream_socket_client()` vs `fsockopen()` under the hood; pick whichever you prefer, or implement `Socket\SocketInterface` to supply your own (e.g. for TLS wrappers or unit-test stubs).

Both transports accept a blocking timeout (seconds, default 1) that controls how long a single read waits for data before reporting "no data yet":

```
use Matasar\PhpTcp\Socket\FSocket;

new FSocket(2); // wait up to 2 seconds per read cycle
new FSocket(0); // non-blocking mode
```

Client settings
---------------

[](#client-settings)

```
use Matasar\PhpTcp\Client;
use Matasar\PhpTcp\Socket\FSocket;

$client = new Client('hostname', 1234, new FSocket());

$client->setChunkSize(16384);        // read data by 16 KB per cycle (default 8 KB).
$client->setPollInterval(5000);      // wait 5 ms between data availability checks (default 1 ms).
$client->setDelimiter("\n");         // treat "\n" as the end of a response (see below).
$client->setLogger(new PsrLogger()); // any PSR-3 logger, for debugging.

$client->connect(5); // connection timeout in seconds (default 2).
```

Response framing
----------------

[](#response-framing)

By default, the client considers a response complete when the server stops sending data for a moment (a silent interval on the stream). This works without any protocol knowledge, but it has two downsides: every read costs an extra blocking-timeout interval, and a server that stalls mid-response can have its reply cut short.

If your protocol marks the end of a message — like line-based protocols such as JSON-RPC over TCP — set a delimiter instead:

```
$client->setDelimiter("\n");
```

With a delimiter set, the client returns as soon as the response ends with the delimiter (the delimiter is kept in the response data). It throws a `RequestException` if a complete response does not arrive within the request timeout, and a `ConnectionException` if the connection is closed before the response is completed.

Error handling
--------------

[](#error-handling)

All exceptions live under `Matasar\PhpTcp\Exception`:

ExceptionThrown when`ConnectionException`Connection could not be established, is already open, was closed by the peer, or the stream broke mid-transfer.`RequestException`No (or no complete) response arrived within the request timeout.`SocketException`Low-level transport failure; wrapped into `ConnectionException` by `connect()`.```
use Matasar\PhpTcp\Exception\ConnectionException;
use Matasar\PhpTcp\Exception\RequestException;

try {
    $client->connect();
    $response = $client->request($request);
} catch (ConnectionException $exception) {
    // failed to connect / connection lost
} catch (RequestException $exception) {
    // the server did not respond in time
}
```

Testing
-------

[](#testing)

The test suite runs against PHP 7.4–8.5 in CI.

Locally, the easiest way is Docker — no PHP or Composer installation required:

```
docker run --rm -v $(pwd):/app -w /app composer:lts composer install
docker run --rm -v $(pwd):/app -w /app composer:lts vendor/bin/phpunit
```

Or with a local PHP setup:

```
composer install
vendor/bin/phpunit
```

License
-------

[](#license)

Released under the [MIT license](LICENSE).

###  Health Score

44

—

FairBetter than 90% of packages

Maintenance95

Actively maintained with recent releases

Popularity10

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~893 days

Total

3

Last Release

25d ago

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

1.2.0PHP &gt;=7.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/44632227efd38dd8598ceb71812e223865e994f1f35f027b423469133fb29d6b?d=identicon)[matasarei](/maintainers/matasarei)

---

Top Contributors

[![matasarei](https://avatars.githubusercontent.com/u/6638367?v=4)](https://github.com/matasarei "matasarei (16 commits)")

---

Tags

clientsockettcp-client

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/matasarei-phptcp/health.svg)

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

###  Alternatives

[symfony/http-kernel

Provides a structured process for converting a Request into a Response

8.1k886.6M9.7k](/packages/symfony-http-kernel)[symfony/http-client

Provides powerful methods to fetch HTTP resources synchronously or asynchronously

2.0k347.8M5.6k](/packages/symfony-http-client)[zircote/swagger-php

Generate interactive documentation for your RESTful API using PHP attributes (preferred) or PHPDoc annotations

5.3k148.6M671](/packages/zircote-swagger-php)[matomo/matomo

Matomo is the leading Free/Libre open analytics platform

21.7k39.6k](/packages/matomo-matomo)[api-platform/metadata

API Resource-oriented metadata attributes and factories

275.5M254](/packages/api-platform-metadata)[tempest/framework

The PHP framework that gets out of your way.

2.3k37.6k21](/packages/tempest-framework)

PHPackages © 2026

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