# Socket
[![Build Status](https://travis-ci.org/reactphp/socket.svg?branch=master)](https://travis-ci.org/reactphp/socket)
Async, streaming plaintext TCP/IP and secure TLS socket server and client
connections for [ReactPHP](https://reactphp.org/).
The socket library provides re-usable interfaces for a socket-layer
server and client based on the [`EventLoop`](https://github.com/reactphp/event-loop)
and [`Stream`](https://github.com/reactphp/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](#quickstart-example)
* [Connection usage](#connection-usage)
* [ConnectionInterface](#connectioninterface)
* [getRemoteAddress()](#getremoteaddress)
* [getLocalAddress()](#getlocaladdress)
* [Server usage](#server-usage)
* [ServerInterface](#serverinterface)
* [connection event](#connection-event)
* [error event](#error-event)
* [getAddress()](#getaddress)
* [pause()](#pause)
* [resume()](#resume)
* [close()](#close)
* [Server](#server)
* [Advanced server usage](#advanced-server-usage)
* [TcpServer](#tcpserver)
* [SecureServer](#secureserver)
* [UnixServer](#unixserver)
* [LimitingServer](#limitingserver)
* [getConnections()](#getconnections)
* [Client usage](#client-usage)
* [ConnectorInterface](#connectorinterface)
* [connect()](#connect)
* [Connector](#connector)
* [Advanced client usage](#advanced-client-usage)
* [TcpConnector](#tcpconnector)
* [DnsConnector](#dnsconnector)
* [SecureConnector](#secureconnector)
* [TimeoutConnector](#timeoutconnector)
* [UnixConnector](#unixconnector)
* [FixUriConnector](#fixeduriconnector)
* [Install](#install)
* [Tests](#tests)
* [License](#license)
## Quickstart example
Here is a server that closes the connection if you send it anything:
```php
$loop = React\EventLoop\Factory::create();
$socket = new React\Socket\Server('127.0.0.1:8080', $loop);
$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();
});
});
$loop->run();
```
See also the [examples](examples).
Here's a client that outputs the output of said server and then attempts to
send it a string:
```php
$loop = React\EventLoop\Factory::create();
$connector = new React\Socket\Connector($loop);
$connector->connect('127.0.0.1:8080')->then(function (React\Socket\ConnectionInterface $connection) use ($loop) {
$connection->pipe(new React\Stream\WritableResourceStream(STDOUT, $loop));
$connection->write("Hello World!\n");
});
$loop->run();
```
## 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`](https://github.com/reactphp/stream#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`](#serverinterface) and
used by all classes implementing the [`ConnectorInterface`](#connectorinterface).
Because the `ConnectionInterface` implements the underlying
[`DuplexStreamInterface`](https://github.com/reactphp/stream#duplexstreaminterface)
you can use any of its events and methods as usual:
```php
$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`](https://github.com/reactphp/stream#duplexstreaminterface).
#### getRemoteAddress()
The `getRemoteAddress(): ?string` method returns the full remote address
(URI) where this connection has been established with.
```php
$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:
```php
$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.
```php
$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()`](#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`](https://github.com/igorw/evenement)
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:
```php
$server->on('connection', function (React\Socket\ConnectionInterface $connection) {
echo 'new connection' . PHP_EOL;
});
```
See also the [`ConnectionInterface`](#connectioninterface) f