PHPackages                             icicleio/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. [Queues &amp; Workers](/categories/queues)
4. /
5. icicleio/socket

ActiveLibrary[Queues &amp; Workers](/categories/queues)

icicleio/socket
===============

Asynchronous stream socket server and client for Icicle.

v0.5.3(10y ago)1650.9k↓16.7%2[4 issues](https://github.com/icicleio/socket/issues)4MITPHP

Since Jul 2Pushed 9y ago3 watchersCompare

[ Source](https://github.com/icicleio/socket)[ Packagist](https://packagist.org/packages/icicleio/socket)[ Docs](http://icicle.io)[ RSS](/packages/icicleio-socket/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (3)Versions (16)Used By (4)

Asynchronous Sockets for Icicle
===============================

[](#asynchronous-sockets-for-icicle)

This library is a component for [Icicle](https://github.com/icicleio/icicle), providing an asynchronous stream socket server, connector, and datagram. Like other Icicle components, this library uses [Coroutines](//github.com/icicleio/icicle/wiki/Coroutines) built from [Awaitables](https://github.com/icicleio/icicle/wiki/Awaitables) and [Generators](http://www.php.net/manual/en/language.generators.overview.php) to make writing asynchronous code more like writing synchronous code.

[![Build Status](https://camo.githubusercontent.com/e9f3dbd84e894a61902ed9354ddefaf9bcf6ae6747bf241150bfd952c5525429/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f696369636c65696f2f736f636b65742f76312e782e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/icicleio/socket)[![Coverage Status](https://camo.githubusercontent.com/29ba0dc20d5843ef682ae3cb1c063cbf601221f301d3a6f02461a92d8536b836/68747470733a2f2f696d672e736869656c64732e696f2f636f766572616c6c732f696369636c65696f2f736f636b65742f76312e782e7376673f7374796c653d666c61742d737175617265)](https://coveralls.io/r/icicleio/socket)[![Semantic Version](https://camo.githubusercontent.com/9b0e0d6e9bfd14bd76f97a95ccbca6a884f9e26568703ff1ce72c3168226d046/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f696369636c65696f2f736f636b65742e7376673f7374796c653d666c61742d737175617265)](http://semver.org)[![MIT License](https://camo.githubusercontent.com/90e4cf934cd29235ff04c289adb69ddc95b1c4fd67dba9ec9b3f0f6b84c0cca9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f696369636c65696f2f736f636b65742e7376673f7374796c653d666c61742d737175617265)](LICENSE)[![@icicleio on Twitter](https://camo.githubusercontent.com/fb16a2e03bb85dd9926a15e837d3754b7766046281e2698271930aadbcd972cf/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f747769747465722d253430696369636c65696f2d3531383963372e7376673f7374796c653d666c61742d737175617265)](https://twitter.com/icicleio)

##### Requirements

[](#requirements)

- PHP 5.5+ for v0.5.x branch (current stable) and v1.x branch (mirrors current stable)
- PHP 7 for v2.0 branch (under development) supporting generator delegation and return expressions

##### Suggested

[](#suggested)

- [openssl extension](http://php.net/manual/en/book.openssl.php): Enables using SSL/TLS on sockets.

##### Installation

[](#installation)

The recommended way to install is with the [Composer](http://getcomposer.org/) package manager. (See the [Composer installation guide](https://getcomposer.org/doc/00-intro.md) for information on installing and using Composer.)

Run the following command to use this library in your project:

```
composer require icicleio/socket
```

You can also manually edit `composer.json` to add this library as a project requirement.

```
// composer.json
{
    "require": {
        "icicleio/socket": "^0.5"
    }
}
```

The socket component implements network sockets as coroutine-based streams, server, and datagram. Creating a server and accepting connections is very simple, requiring only a few lines of code.

The example below implements a simple HTTP server listening on 127.0.0.1:8080 that responds to any request with the contents of the client request as the body of the response. This example is implemented using coroutines (see the [Coroutine API documentation](https://github.com/icicleio/icicle/wiki/Coroutines)) and the basic sockets provided by this package.

```
use Icicle\Coroutine\Coroutine;
use Icicle\Loop;
use Icicle\Socket\Server\DefaultServerFactory;
use Icicle\Socket\Server\Server;
use Icicle\Socket\Socket;

$server = (new DefaultServerFactory())->create('localhost', 8080);

$generator = function (Server $server) {
    printf("Server listening on %s:%d\n", $server->getAddress(), $server->getPort());

    $generator = function (Socket $socket) {
        $request = '';
        do {
            $request .= (yield $socket->read(0, "\n"));
        } while (substr($request, -4) !== "\r\n\r\n");

        $message = sprintf("Received the following request:\r\n\r\n%s", $request);

        $data  = "HTTP/1.1 200 OK\r\n";
        $data .= "Content-Type: text/plain\r\n";
        $data .= sprintf("Content-Length: %d\r\n", strlen($message));
        $data .= "Connection: close\r\n";
        $data .= "\r\n";
        $data .= $message;

        yield $socket->write($data);

        $socket->close();
    };

    while ($server->isOpen()) {
        // Handle client in a separate coroutine so this coroutine is not blocked.
        $coroutine = new Coroutine($generator(yield $server->accept()));
        $coroutine->done(null, function ($exception) {
            printf("Client error: %s\n", $exception->getMessage());
        });
    }
};

$coroutine = new Coroutine($generator($server));
$coroutine->done();

Loop\run();
```

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

[](#documentation)

- [Server](#server)
    - [BasicServer Constructor](#basicserver-constructor) - Creates a server from a stream socket server resource.
    - [accept()](#accept) - A coroutine that is resolved when a client connects.
    - [getAddress()](#getaddress) - Returns the address of the server.
    - [getPort()](#getport) - Returns the port of the server.
- [ServerFactory](#serverfactory)
    - [create()](#create) - Creates a `Server` on a given host and port.
- [Socket](#socket)
    - [NetworkSocket Constructor](#networksocket-constructor) - Creates a socket object from a stream socket resource.
    - [enableCrypto()](#enablecrypto) - Enables crypto on the socket.
    - [isCryptoEnabled()](#iscryptoenabled) - Determines if crypto is enabled on the socket.
    - [unshift()](#unshift) - Shifts data back to the front of the socket stream.
    - [getLocalAddress()](#getlocaladdress) - Returns the local address of the socket.
    - [getLocalPort()](#getlocalport) - Returns the local port of the socket.
    - [getRemoteAddress()](#getremoteaddress) - Returns the remote address of the socket.
    - [getRemotePort()](#getremoteport) - Returns the remote port of the socket.
- [Connector](#connector)
    - [connect()](#connect) - A coroutine resolved with a `Socket` object when a connection is established.
- [Datagram](#datagram) - UDP socket listener
    - [BasicDatagram Constructor](#basicdatagram-constructor)
    - [receive()](#receive) - Receives data from the datagram.
    - [send()](#send) - Sends data to a address and port.
    - [getAddress()](#getaddress1) - Returns the address of the datagram.
    - [getPort()](#getport1) - Returns the port of the datagram.
- [DatagramFactory](#datagramfactory)
    - [create()](#create1) - Creates a `Datagram` on a given host and port.
- [Functions](#functions)
    - [connect()](#socketconnect) - Uses the global connector to connect to the given IP and port.
    - [connector()](#socketconnector) - Accesses or sets the global connector instance.

#### Function prototypes

[](#function-prototypes)

Prototypes for object instance methods are described below using the following syntax:

```
ClassOrInterfaceName::methodName(ArgumentType $arg): ReturnType
```

Server
------

[](#server)

The `Icicle\Socket\Server\BasicServer` class implements `Icicle\Socket\Server\Server`, a coroutine-based interface for creating a TCP server and accepting connections.

#### BasicServer Constructor

[](#basicserver-constructor)

```
$server = new BasicServer(resource $socket)
```

Creates a server from a stream socket server resource generated from `stream_socket_server()`. Generally it is better to use `Icicle\Socket\Server\DefaultServerFactory` to create a `Icicle\Socket\Server\BasicServer` instance.

---

#### accept()

[](#accept)

```
Server::accept(): Generator
```

A coroutine that is resolved with an object implementing `Icicle\Socket\Socket` when a connection is accepted.

ResolutionTypeDescriptionFulfilled`Icicle\Socket\Socket`Accepted client connection.Rejected`Icicle\Socket\Exception\BusyException`If the server already had an accept pending.Rejected`Icicle\Socket\Exception\UnavailableException`If the server was previously closed.Rejected`Icicle\Socket\Exception\ClosedException`If the server is closed during pending accept.---

#### getAddress()

[](#getaddress)

```
Server::getAddress(): string
```

Returns the local IP address as a string.

---

#### getPort()

[](#getport)

```
Server::getPort(): int
```

Returns the local port.

ServerFactory
-------------

[](#serverfactory)

`Icicle\Socket\Server\DefaultServerFactory` (implements `Icicle\Socket\Server\ServerFactory`) can be used to create server instances from a IP or unix socket path, port number (`null` for unix socket), and list of options.

#### create()

[](#create)

```
ServerFactory::create(
    string $host,
    int $port = null,
    mixed[] $options = []
): Server
```

Creates a server bound and listening on the given ip or unix socket path and port number (`null` for unix socket).

OptionTypeDescription`backlog``int`Connection backlog size. Note that the operating system variable `SOMAXCONN` may set an upper limit and may need to be changed to allow a larger backlog size.`pem``string`Path to PEM file containing certificate and private key to enable SSL on client connections.`passphrase``string`PEM passphrase if applicable.`name``string`Name to use as SNI identifier. If not set, name will be guessed based on `$host`.Socket
------

[](#socket)

`Icicle\Socket\NetworkSocket` objects implement `Icicle\Socket\Socket` and are used as the fulfillment value of the coroutine returned by `Icicle\Socket\Server\BasicServer::accept()` ([see documentation above](#accept)). (Note that `Icicle\Socket\Server\BasicServer` can be easily extended and modified to fulfill accept requests with different objects implementing `Icicle\Socket\Socket`.)

The class extends `Icicle\Stream\Pipe\DuplexPipe`, so it inherits all the readable and writable stream methods as well as adding those below.

#### NetworkSocket Constructor

[](#networksocket-constructor)

```
$socket = new NetworkSocket(resource $socket)
```

Creates a socket object from the given stream socket resource.

---

#### enableCrypto()

[](#enablecrypto)

```
Socket::enableCrypto(int $method, float $timeout = 0): \Generator
```

Enables encryption on the socket. For Socket objects created from `Icicle\Socket\Server\Server::accept()`, a PEM file must have been provided when creating the server socket (see `Icicle\Socket\Server\ServerFactory`). Use the `STREAM_CRYPTO_METHOD_*_SERVER` constants when enabling crypto on remote clients (e.g., created by `Icicle\Socket\Server\Server::accept()`) and the `STREAM_CRYPTO_METHOD_*_CLIENT` constants when enabling crypto on a local client connection (e.g., created by `Icicle\Socket\Connector\Connector::connect()`).

---

#### isCryptoEnabled()

[](#iscryptoenabled)

```
Socket::isCryptoEnabled(): bool
```

Determines if encryption is enabled on the socket.

---

#### unshift()

[](#unshift)

```
Socket::unshift(string $data): void
```

Determines if encryption is enabled on the socket.

---

#### getLocalAddress()

[](#getlocaladdress)

```
Socket::getLocalAddress(): string
```

Returns the local IP address as a string.

---

#### getLocalPort()

[](#getlocalport)

```
Socket::getLocalPort(): int
```

Returns the local port.

---

#### getRemoteAddress()

[](#getremoteaddress)

```
Socket::getRemoteAddress(): string
```

Returns the remote IP address as a string.

---

#### getRemotePort()

[](#getremoteport)

```
Socket::getRemotePort(): int
```

Returns the remote port.

Connector
---------

[](#connector)

The `Icicle\Socket\Connector\DefaultConnector` class (implements `Icicle\Socket\Connector\Connector`) asynchronously connects to a remote server, returning a coroutine that is fulfilled with an instance of `Icicle\Socket\Socket` when the connection is successfully established. Note that the *host should be given as an IP address*, as DNS lookups performed by PHP are synchronous (blocking). If you wish to use domain names instead of IPs, see `Icicle\Dns\Connector\Connector` in the [DNS component](https://github.com/icicleio/dns).

#### connect()

[](#connect)

```
Connector::connect(
    string $host,
    int|null $port,
    mixed[] $options = []
): \Generator
```

Connects asynchronously to the given IP or unix socket path on the given port number (`null` for unix socket).

OptionTypeDescription`protocol``string`The protocol to use, such as tcp, udp, s3, ssh. Defaults to tcp.`timeout``float`Number of seconds until connection attempt times out. Defaults to 10 seconds.`cn``string`Host name (common name) used to verify certificate. e.g., `*.google.com``allow_self_signed``bool`Set to `true` to allow self-signed certificates. Defaults to `false`.`max_depth``int`Max levels of certificate authorities the verifier will transverse. Defaults to 10.`cafile``string`Path to bundle of root certificates to verify against.ResolutionTypeDescriptionFulfilled`Icicle\Socket\Socket`Fulfilled once the connection is established.Rejected`Icicle\Socket\Exception\FailureException`If the connection attempt fails (such as an invalid host).Rejected`Icicle\Awaitable\Exception\TimeoutException`If the connection attempt times out.Datagram
--------

[](#datagram)

The `Icicle\Socket\Datagram\BasicDatagram` class implements `Icicle\Socket\Datagram\Datagram`, a coroutine-based interface for creating a UDP listener and sender.

#### BasicDatagram Constructor

[](#basicdatagram-constructor)

```
$datagram = new BasicDatagram(resource $socket)
```

Creates a datagram from a stream socket server resource generated from `stream_socket_server()`. Generally it is better to use `Icicle\Socket\Datagram\DefaultDatagramFactory` to create a `Icicle\Socket\Datagram\BasicDatagram` instance.

---

#### receive()

[](#receive)

```
Datagram::receive(int $length, float $timeout): Generator
```

A coroutine that is fulfilled with an array when a data is received on the UDP socket (datagram). The array is a 0-indexed array containing the IP address, port, and data received, in that order.

ResolutionTypeDescriptionFulfilled`array`IP address, port, and data received.Rejected`Icicle\Socket\Exception\BusyException`If the server already had an accept pending.Rejected`Icicle\Stream\Exception\UnavailableException`If the server was previously closed.---

#### send()

[](#send)

```
Datagram::send(
    string $address,
    int $port,
    string $data
): \Generator
```

Send the given data to the IP address and port. This coroutine is fulfilled with the amount of data sent once the data has successfully been sent.

ResolutionTypeDescriptionFulfilled`int`Length of data sent.Rejected`Icicle\Socket\Exception\BusyException`If the server already had an accept pending.Rejected`Icicle\Stream\Exception\UnavailableException`If the server was previously closed.Rejected`Icicle\Stream\Exception\ClosedException`If the server is closed during pending accept.---

#### getAddress()

[](#getaddress-1)

```
Datagram::getAddress(): string
```

Returns the local IP address as a string.

---

#### getPort()

[](#getport-1)

```
Datagram::getPort(): int
```

Returns the local port.

DatagramFactory
---------------

[](#datagramfactory)

`Icicle\Socket\Datagram\DefaultDatagramFactory` (implements `Icicle\Socket\Datagram\DatagramFactory`) can be used to create datagram instances from a hostname or unix socket path, port number (`null` for unix socket), and list of options.

#### create()

[](#create-1)

```
DatagramFactory::create(
    string $host,
    int $port = null,
    mixed[] $options = []
): Datagram
```

Creates a datagram bound and listening on the given IP and port number. No options are defined in this implementation.

Functions
---------

[](#functions)

#### Socket\\connect()

[](#socketconnect)

```
Icicle\Socket\connect(
    string $ip,
    int|null $port,
    array $options = []
): \Generator
```

Connects asynchronously to the given host on the given port. Uses the global connector interface that can be set using `Icicle\Socket\connector()`.

OptionTypeDescription`protocol``string`The protocol to use, such as tcp, udp, s3, ssh. Defaults to tcp.`timeout``float`Number of seconds until connection attempt times out. Defaults to 10 seconds.`cn``string`Host name (common name) used to verify certificate. e.g., `*.google.com``allow_self_signed``bool`Set to `true` to allow self-signed certificates. Defaults to `false`.`max_depth``int`Max levels of certificate authorities the verifier will transverse. Defaults to 10.`cafile``string`Path to bundle of root certificates to verify against.ResolutionTypeDescriptionFulfilled`Icicle\Socket\Socket`Fulfilled once the connection is established.Rejected`Icicle\Socket\Exception\FailureException`If the connection attempt fails (such as an invalid host).Rejected`Icicle\Awaitable\Exception\TimeoutException`If the connection attempt times out.---

#### Socket\\connector()

[](#socketconnector)

```
Icicle\Socket\connector(
    Connector|null $connector = null
): Connector
```

Gets the global connector instance. If a `Connector` instance is provided, that instance is set as the global connector instance.

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance15

Infrequent updates — may be unmaintained

Popularity36

Limited adoption so far

Community18

Small or concentrated contributor base

Maturity61

Established project with proven stability

 Bus Factor1

Top contributor holds 99.2% 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 ~16 days

Total

14

Last Release

3755d ago

Major Versions

v0.5.3 → 1.x-dev2016-02-06

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/1628287?v=4)[Aaron Piotrowski](/maintainers/Trowski)[@trowski](https://github.com/trowski)

---

Top Contributors

[![trowski](https://avatars.githubusercontent.com/u/1628287?v=4)](https://github.com/trowski "trowski (126 commits)")[![sagebind](https://avatars.githubusercontent.com/u/2192863?v=4)](https://github.com/sagebind "sagebind (1 commits)")

---

Tags

streamasyncasynchronousclientserverSocket

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[icicleio/icicle

Icicle is a PHP library for writing asynchronous code using synchronous coding techniques.

1.1k150.9k14](/packages/icicleio-icicle)[react/socket

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

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

A server side alternative implementation of socket.io in PHP based on Workerman

2.3k578.6k16](/packages/workerman-phpsocketio)[react/datagram

Event-driven UDP datagram socket client and server for ReactPHP

99759.5k36](/packages/react-datagram)[clue/socket-raw

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

35111.1M48](/packages/clue-socket-raw)[icicleio/concurrent

Concurrency component for Icicle.

17235.8k2](/packages/icicleio-concurrent)

PHPackages © 2026

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