SkillAgentSearch skills...

Socket

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

Install / Use

/learn @reactphp/Socket
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

Socket

CI status installs on Packagist

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

Development version: This branch contains the code for the upcoming v3 release. For the code of the current stable v1 release, check out the 1.x branch.

The upcoming v3 release will be the way forward for this package. However, we will still actively support v1 for those not yet on the latest version. See also installation instructions for more details.

The socket library provides re-usable interfaces for a socket-layer server and client based on the EventLoop and Stream components. Its server component allows you to build networking servers that accept incoming connections from networking clients (such as an HTTP server). Its client component allows you to build networking clients that establish outgoing connections to networking servers (such as an HTTP or database client). This library provides async, streaming means for all of this, so you can handle multiple concurrent connections without blocking.

Table of Contents

Quickstart example

Here is a server that closes the connection if you send it anything:

$socket = new React\Socket\SocketServer('127.0.0.1:8080');

$socket->on('connection', function (React\Socket\ConnectionInterface $connection) {
    $connection->write("Hello " . $connection->getRemoteAddress() . "!\n");
    $connection->write("Welcome to this amazing server!\n");
    $connection->write("Here's a tip: don't say anything.\n");

    $connection->on('data', function ($data) use ($connection) {
        $connection->close();
    });
});

See also the examples.

Here's a client that outputs the output of said server and then attempts to send it a string:

$connector = new React\Socket\Connector();

$connector->connect('127.0.0.1:8080')->then(function (React\Socket\ConnectionInterface $connection) {
    $connection->pipe(new React\Stream\WritableResourceStream(STDOUT));
    $connection->write("Hello World!\n");
}, function (Exception $e) {
    echo 'Error: ' . $e->getMessage() . PHP_EOL;
});

Connection usage

ConnectionInterface

The ConnectionInterface is used to represent any incoming and outgoing connection, such as a normal TCP/IP connection.

An incoming or outgoing connection is a duplex stream (both readable and writable) that implements React's DuplexStreamInterface. It contains additional properties for the local and remote address (client IP) where this connection has been established to/from.

Most commonly, instances implementing this ConnectionInterface are emitted by all classes implementing the ServerInterface and used by all classes implementing the ConnectorInterface.

Because the ConnectionInterface implements the underlying DuplexStreamInterface you can use any of its events and methods as usual:

$connection->on('data', function ($chunk) {
    echo $chunk;
});

$connection->on('end', function () {
    echo 'ended';
});

$connection->on('error', function (Exception $e) {
    echo 'error: ' . $e->getMessage();
});

$connection->on('close', function () {
    echo 'closed';
});

$connection->write($data);
$connection->end($data = null);
$connection->close();
// …

For more details, see the DuplexStreamInterface.

getRemoteAddress()

The getRemoteAddress(): ?string method returns the full remote address (URI) where this connection has been established with.

$address = $connection->getRemoteAddress();
echo 'Connection with ' . $address . PHP_EOL;

If the remote address can not be determined or is unknown at this time (such as after the connection has been closed), it MAY return a NULL value instead.

Otherwise, it will return the full address (URI) as a string value, such as tcp://127.0.0.1:8080, tcp://[::1]:80, tls://127.0.0.1:443, unix://example.sock or unix:///path/to/example.sock. Note that individual URI components are application specific and depend on the underlying transport protocol.

If this is a TCP/IP based connection and you only want the remote IP, you may use something like this:

$address = $connection->getRemoteAddress();
$ip = trim(parse_url($address, PHP_URL_HOST), '[]');
echo 'Connection with ' . $ip . PHP_EOL;

getLocalAddress()

The getLocalAddress(): ?string method returns the full local address (URI) where this connection has been established with.

$address = $connection->getLocalAddress();
echo 'Connection with ' . $address . PHP_EOL;

If the local address can not be determined or is unknown at this time (such as after the connection has been closed), it MAY return a NULL value instead.

Otherwise, it will return the full address (URI) as a string value, such as tcp://127.0.0.1:8080, tcp://[::1]:80, tls://127.0.0.1:443, unix://example.sock or unix:///path/to/example.sock. Note that individual URI components are application specific and depend on the underlying transport protocol.

This method complements the getRemoteAddress() method, so they should not be confused.

If your TcpServer instance is listening on multiple interfaces (e.g. using the address 0.0.0.0), you can use this method to find out which interface actually accepted this connection (such as a public or local interface).

If your system has multiple interfaces (e.g. a WAN and a LAN interface), you can use this method to find out which interface was actually used for this connection.

Server usage

ServerInterface

The ServerInterface is responsible for providing an interface for accepting incoming streaming connections, such as a normal TCP/IP connection.

Most higher-level components (such as a HTTP server) accept an instance implementing this interface to accept incoming streaming connections. This is usually done via dependency injection, so it's fairly simple to actually swap this implementation against any other implementation of this interface. This means that you SHOULD typehint against this interface instead of a concrete implementation of this interface.

Besides defining a few methods, this interface also implements the EventEmitterInterface which allows you to react to certain events.

connection event

The connection event will be emitted whenever a new connection has been established, i.e. a new client connects to this server socket:

$socket->on('connection', function (React\Socket\ConnectionInterface $connection) {
    echo 'new connection' . PHP_EOL;
});

See also the ConnectionInterface for more details about handling the incoming connection.

error event

The error event will be emitted whenever there's an error accepting a new connection from a client.

$socket->on('error', function (Exception $e) {
    echo 'error: ' . $e->getMessage() . PHP_EOL;
});

Note that this is not a fatal error event, i.e. the server keeps listening for new connections even after this event.

getAddress()

The getAddress(): ?string method can be used to return the full address (URI) this server is currently listening on.

$address = $socket->getAddress();
echo 'Server listening on ' . $address . PHP_EOL;

If the address can not be determined or is unknown at this time (such as after the socket has been closed), it MAY return a NULL value instead.

Otherwise, it will return the full address (URI) as a string value, such as tcp://127.0.0.1:8080, tcp://[::1]:80, tls://127.0.0.1:443 unix://example.sock or unix:///path/to/example.sock. Note that individual URI components are application specific and depend on the underlying transport protocol.

If this is a TCP/IP based server and you only want the local port, you may use something like this:

$address = $socket->getAddress();
$port = parse_url($address, PHP_URL_PORT);
echo 'Server listening on port ' . $port . PHP_EOL;

pause()

The pause(): void method can be us

View on GitHub
GitHub Stars1.3k
CategoryDevelopment
Updated13d ago
Forks158

Languages

PHP

Security Score

100/100

Audited on Mar 14, 2026

No findings