PHPackages                             werkint/reactphp-socket-client - 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. werkint/reactphp-socket-client

Abandoned → [werkint/reactphp-socket-client](/?search=werkint%2Freactphp-socket-client)Library

werkint/reactphp-socket-client
==============================

Async connector to open TCP/IP and SSL/TLS based connections.

v0.5.3(9y ago)11.3kMITPHPPHP &gt;=5.3.0

Since Apr 14Pushed 9y ago4 watchersCompare

[ Source](https://github.com/Werkint/socket-client)[ Packagist](https://packagist.org/packages/werkint/reactphp-socket-client)[ RSS](/packages/werkint-reactphp-socket-client/feed)WikiDiscussions master Synced 2mo ago

READMEChangelogDependencies (6)Versions (17)Used By (0)

SocketClient Component
======================

[](#socketclient-component)

[![Build Status](https://camo.githubusercontent.com/0d33b5f25e658ce81a405b53a7f5ddcc575d4d5ebdece239f09bf4fbd5045908/68747470733a2f2f7365637572652e7472617669732d63692e6f72672f72656163747068702f736f636b65742d636c69656e742e706e673f6272616e63683d6d6173746572)](http://travis-ci.org/reactphp/socket-client) [![Code Climate](https://camo.githubusercontent.com/62f09c8c5e7d1d27bb58c5c51f592debe2eedbeb973d3cf1643f9d3c04826a29/68747470733a2f2f636f6465636c696d6174652e636f6d2f6769746875622f72656163747068702f736f636b65742d636c69656e742f6261646765732f6770612e737667)](https://codeclimate.com/github/reactphp/socket-client)

Async Connector to open TCP/IP and SSL/TLS based connections.

Introduction
------------

[](#introduction)

Think of this library as an async version of [`fsockopen()`](http://www.php.net/function.fsockopen) or [`stream_socket_client()`](http://php.net/function.stream-socket-client).

Before you can actually transmit and receive data to/from a remote server, you have to establish a connection to the remote end. Establishing this connection through the internet/network takes some time as it requires several steps in order to complete:

1. Resolve remote target hostname via DNS (+cache)
2. Complete TCP handshake (2 roundtrips) with remote target IP:port
3. Optionally enable SSL/TLS on the new resulting connection

Usage
-----

[](#usage)

In order to use this project, you'll need the following react boilerplate code to initialize the main loop.

```
$loop = React\EventLoop\Factory::create();
```

### ConnectorInterface

[](#connectorinterface)

The `ConnectorInterface` is responsible for providing an interface for establishing streaming connections, such as a normal TCP/IP connection.

This is the main interface defined in this package and it is used throughout React's vast ecosystem.

Most higher-level components (such as HTTP, database or other networking service clients) accept an instance implementing this interface to create their TCP/IP connection to the underlying networking service. This is usually done via dependency injection, so it's fairly simple to actually swap this implementation against any other implementation of this interface.

The interface only offers a single method:

#### create()

[](#create)

The `create(string $host, int $port): PromiseInterface` method can be used to establish a streaming connection. It returns a [Promise](https://github.com/reactphp/promise) which either fulfills with a [Stream](https://github.com/reactphp/stream) or rejects with an `Exception`:

```
$connector->create('google.com', 443)->then(
    function (Stream $stream) {
        // connection successfully established
    },
    function (Exception $error) {
        // failed to connect due to $error
    }
);
```

The returned Promise SHOULD be implemented in such a way that it can be cancelled when it is still pending. Cancelling a pending promise SHOULD reject its value with an `Exception`. It SHOULD clean up any underlying resources and references as applicable:

```
$promise = $connector->create($host, $port);

$promise->cancel();
```

### Async TCP/IP connections

[](#async-tcpip-connections)

The `React\SocketClient\TcpConnector` class implements the [`ConnectorInterface`](#connectorinterface) and allows you to create plaintext TCP/IP connections to any IP-port-combination:

```
$tcpConnector = new React\SocketClient\TcpConnector($loop);

$tcpConnector->create('127.0.0.1', 80)->then(function (React\Stream\Stream $stream) {
    $stream->write('...');
    $stream->end();
});

$loop->run();
```

See also the [first example](examples).

Pending connection attempts can be cancelled by cancelling its pending promise like so:

```
$promise = $tcpConnector->create($host, $port);

$promise->cancel();
```

Calling `cancel()` on a pending promise will close the underlying socket resource, thus cancelling the pending TCP/IP connection, and reject the resulting promise.

You can optionally pass additional [socket context options](http://php.net/manual/en/context.socket.php)to the constructor like this:

```
$tcpConnector = new React\SocketClient\TcpConnector($loop, array(
    'bindto' => '192.168.0.1:0'
));
```

Note that this class only allows you to connect to IP-port-combinations. If you want to connect to hostname-port-combinations, see also the following chapter.

### DNS resolution

[](#dns-resolution)

The `DnsConnector` class implements the [`ConnectorInterface`](#connectorinterface) and allows you to create plaintext TCP/IP connections to any hostname-port-combination.

It does so by decorating a given `TcpConnector` instance so that it first looks up the given domain name via DNS (if applicable) and then establishes the underlying TCP/IP connection to the resolved target IP address.

Make sure to set up your DNS resolver and underlying TCP connector like this:

```
$dnsResolverFactory = new React\Dns\Resolver\Factory();
$dns = $dnsResolverFactory->createCached('8.8.8.8', $loop);

$dnsConnector = new React\SocketClient\DnsConnector($tcpConnector, $dns);

$dnsConnector->create('www.google.com', 80)->then(function (React\Stream\Stream $stream) {
    $stream->write('...');
    $stream->end();
});

$loop->run();
```

See also the [first example](examples).

Pending connection attempts can be cancelled by cancelling its pending promise like so:

```
$promise = $dnsConnector->create($host, $port);

$promise->cancel();
```

Calling `cancel()` on a pending promise will cancel the underlying DNS lookup and/or the underlying TCP/IP connection and reject the resulting promise.

The legacy `Connector` class can be used for backwards-compatiblity reasons. It works very much like the newer `DnsConnector` but instead has to be set up like this:

```
$connector = new React\SocketClient\Connector($loop, $dns);

$connector->create('www.google.com', 80)->then($callback);
```

### Async SSL/TLS connections

[](#async-ssltls-connections)

The `SecureConnector` class implements the [`ConnectorInterface`](#connectorinterface) and allows you to create secure TLS (formerly known as SSL) connections to any hostname-port-combination.

It does so by decorating a given `DnsConnector` instance so that it first creates a plaintext TCP/IP connection and then enables TLS encryption on this stream.

```
$secureConnector = new React\SocketClient\SecureConnector($dnsConnector, $loop);

$secureConnector->create('www.google.com', 443)->then(function (React\Stream\Stream $stream) {
    $stream->write("GET / HTTP/1.0\r\nHost: www.google.com\r\n\r\n");
    ...
});

$loop->run();
```

See also the [second example](examples).

Pending connection attempts can be cancelled by cancelling its pending promise like so:

```
$promise = $secureConnector->create($host, $port);

$promise->cancel();
```

Calling `cancel()` on a pending promise will cancel the underlying TCP/IP connection and/or the SSL/TLS negonation and reject the resulting promise.

You can optionally pass additional [SSL context options](http://php.net/manual/en/context.ssl.php)to the constructor like this:

```
$secureConnector = new React\SocketClient\SecureConnector($dnsConnector, $loop, array(
    'verify_peer' => false,
    'verify_peer_name' => false
));
```

> Advanced usage: Internally, the `SecureConnector` has to set the required *context options* on the underlying stream resource. It should therefor be used with a `TcpConnector` somewhere in the connector stack so that it can allocate an empty *context* resource for each stream resource. Failing to do so may result in some hard to trace race conditions, because all stream resources will use a single, shared *default context* resource otherwise.

### Connection timeouts

[](#connection-timeouts)

The `TimeoutConnector` class implements the [`ConnectorInterface`](#connectorinterface) and allows you to add timeout handling to any existing connector instance.

It does so by decorating any given [`ConnectorInterface`](#connectorinterface)instance and starting a timer that will automatically reject and abort any underlying connection attempt if it takes too long.

```
$timeoutConnector = new React\SocketClient\TimeoutConnector($connector, 3.0, $loop);

$timeoutConnector->create('google.com', 80)->then(function (React\Stream\Stream $stream) {
    // connection succeeded within 3.0 seconds
});
```

See also any of the [examples](examples).

Pending connection attempts can be cancelled by cancelling its pending promise like so:

```
$promise = $timeoutConnector->create($host, $port);

$promise->cancel();
```

Calling `cancel()` on a pending promise will cancel the underlying connection attempt, abort the timer and reject the resulting promise.

### Unix domain sockets

[](#unix-domain-sockets)

The `UnixConnector` class implements the [`ConnectorInterface`](#connectorinterface) and allows you to connect to Unix domain socket (UDS) paths like this:

```
$connector = new React\SocketClient\UnixConnector($loop);

$connector->create('/tmp/demo.sock')->then(function (React\Stream\Stream $stream) {
    $stream->write("HELLO\n");
});

$loop->run();
```

Connecting to Unix domain sockets is an atomic operation, i.e. its promise will settle (either resolve or reject) immediately. As such, calling `cancel()` on the resulting promise has no effect.

Install
-------

[](#install)

The recommended way to install this library is [through Composer](http://getcomposer.org). [New to Composer?](http://getcomposer.org/doc/00-intro.md)

This will install the latest supported version:

```
$ composer require react/socket-client:^0.5.3
```

More details about version upgrades can be found in the [CHANGELOG](CHANGELOG.md).

Tests
-----

[](#tests)

To run the test suite, you need PHPUnit. Go to the project root and run:

```
$ phpunit
```

The test suite also contains some optional integration tests which operate on a TCP/IP socket server and an optional TLS/SSL terminating proxy in front of it. The underlying TCP/IP socket server will be started automatically, whereas the TLS/SSL terminating proxy has to be started and enabled like this:

```
$ stunnel -f -p stunnel.pem -d 6001 -r 6000 &
$ TEST_SECURE=6001 TEST_PLAIN=6000 phpunit
```

See also the [Travis configuration](.travis.yml) for details on how to set up the TLS/SSL terminating proxy and the required certificate file (`stunnel.pem`) if you're unsure.

###  Health Score

29

—

LowBetter than 59% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity16

Limited adoption so far

Community16

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor2

2 contributors hold 50%+ of commits

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 ~91 days

Recently: every ~8 days

Total

16

Last Release

3414d ago

PHP version history (3 changes)v0.3.0PHP &gt;=5.3.3

v0.4.1PHP &gt;=5.4.0

v0.5.0PHP &gt;=5.3.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/533d0c99c4e0c7413a1dcce2d81c37ecf94883e6377d274d6f43247a399bb268?d=identicon)[nick4fake](/maintainers/nick4fake)

---

Top Contributors

[![clue](https://avatars.githubusercontent.com/u/776829?v=4)](https://github.com/clue "clue (67 commits)")[![cboden](https://avatars.githubusercontent.com/u/617694?v=4)](https://github.com/cboden "cboden (40 commits)")[![igorw](https://avatars.githubusercontent.com/u/88061?v=4)](https://github.com/igorw "igorw (29 commits)")[![WyriHaximus](https://avatars.githubusercontent.com/u/147145?v=4)](https://github.com/WyriHaximus "WyriHaximus (4 commits)")[![jsor](https://avatars.githubusercontent.com/u/55574?v=4)](https://github.com/jsor "jsor (1 commits)")[![e3betht](https://avatars.githubusercontent.com/u/1811561?v=4)](https://github.com/e3betht "e3betht (1 commits)")[![DaveRandom](https://avatars.githubusercontent.com/u/2396425?v=4)](https://github.com/DaveRandom "DaveRandom (1 commits)")[![alexmace](https://avatars.githubusercontent.com/u/207391?v=4)](https://github.com/alexmace "alexmace (1 commits)")[![elliot](https://avatars.githubusercontent.com/u/9938?v=4)](https://github.com/elliot "elliot (1 commits)")

---

Tags

Socket

### Embed Badge

![Health badge](/badges/werkint-reactphp-socket-client/health.svg)

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

###  Alternatives

[react/socket

Async, streaming plaintext TCP/IP and secure TLS socket server and client connections for ReactPHP

1.3k116.9M402](/packages/react-socket)[react/react

ReactPHP: Event-driven, non-blocking I/O with PHP.

9.1k3.6M63](/packages/react-react)[ccxt/ccxt

A cryptocurrency trading API with more than 100 exchanges in JavaScript / TypeScript / Python / C# / PHP / Go

41.5k328.9k1](/packages/ccxt-ccxt)[league/geotools

Geo-related tools PHP 7.3+ library

1.4k5.3M26](/packages/league-geotools)[team-reflex/discord-php

An unofficial API to interact with the voice and text service Discord.

1.1k379.4k24](/packages/team-reflex-discord-php)[clue/docker-react

Async, event-driven access to the Docker Engine API, built on top of ReactPHP.

113154.9k1](/packages/clue-docker-react)

PHPackages © 2026

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