Async, streaming plaintext TCP/IP and secure TLS based connections for ReactPHP
You can think of this library as an async version of
fsockopen()
or
stream_socket_client()
.
If you want to transmit and receive data to/from a remote server, you first
have to establish a connection to the remote end.
Establishing this connection through the internet/network may take some time
as it requires several steps (such as resolving target hostname, completing
TCP/IP handshake and enabling TLS) in order to complete.
This component provides an async version of all this so you can establish and
handle multiple connections without blocking.
Table of Contents
In order to use this project, you'll need the following react boilerplate code to initialize the main loop.
$loop = React\EventLoop\Factory::create();
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:
The connect(string $uri): PromiseInterface<ConnectionInterface, Exception>
method
can be used to create a streaming connection to the given remote address.
It returns a Promise which either
fulfills with a stream implementing ConnectionInterface
on success or rejects with an Exception
if the connection is not successful:
$connector->connect('google.com:443')->then(
function (ConnectionInterface $connection) {
// connection successfully established
},
function (Exception $error) {
// failed to connect due to $error
}
);
See also ConnectionInterface
for more details.
The returned Promise MUST be implemented in such a way that it can be
cancelled when it is still pending. Cancelling a pending promise MUST
reject its value with an Exception
. It SHOULD clean up any underlying
resources and references as applicable:
$promise = $connector->connect($uri);
$promise->cancel();
The ConnectionInterface
is used to represent any outgoing connection,
such as a normal TCP/IP connection.
An 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
where this connection has been established to.
Most commonly, instances implementing this ConnectionInterface
are returned
by all classes implementing the ConnectorInterface
.
Note that this interface is only to be used to represent the client-side end of an outgoing connection. It MUST NOT be used to represent an incoming connection in a server-side context. If you want to accept incoming connections, use the
Socket
component instead.
Because the ConnectionInterface
implements the underlying
DuplexStreamInterface
you can use any of its events and methods as usual:
$connection->on('data', function ($chunk) {
echo $data;
});
$conenction->on('close', function () {
echo 'closed';
});
$connection->write($data);
$connection->end($data = null);
$connection->close();
// …
For more details, see the
DuplexStreamInterface
.
The getRemoteAddress(): ?string
method can be used to
return the remote address (IP and port) where this connection has been
established to.
$address = $connection->getRemoteAddress();
echo 'Connected to ' . $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 remote address as a string value. 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('tcp://' . $address, PHP_URL_HOST), '[]');
echo 'Connected to ' . $ip . PHP_EOL;
The getLocalAddress(): ?string
method can be used to
return the full local address (IP and port) where this connection has been
established from.
$address = $connection->getLocalAddress();
echo 'Connected via ' . $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 local address as a string value.
This method complements the getRemoteAddress()
method,
so they should not be confused.
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.
The React\SocketClient\TcpConnector
class implements the
ConnectorInterface
and allows you to create plaintext
TCP/IP connections to any IP-port-combination:
$tcpConnector = new React\SocketClient\TcpConnector($loop);
$tcpConnector->connect('127.0.0.1:80')->then(function (ConnectionInterface $connection) {
$connection->write('...');
$connection->end();
});
$loop->run();
See also the first example.
Pending connection attempts can be cancelled by cancelling its pending promise like so:
$promise = $tcpConnector->connect('127.0.0.1:80');
$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 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.
The DnsConnector
class implements the
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->connectCached('8.8.8.8', $loop);
$dnsConnector = new React\SocketClient\DnsConnector($tcpConnector, $dns);
$dnsConnector->connect('www.google.com:80')->then(function (ConnectionInterface $connection) {
$connection->write('...');
$connection->end();
});
$loop->run();
See also the first example.
Pending connection attempts can be cancelled by cancelling its pending promise like so:
$promise = $dnsConnector->connect('www.google.com:80');
$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->connect('www.google.com:80')->then($callback);
The SecureConnector
class implements the
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->connect('www.google.com:443')->then(function (ConnectionInterface $connection) {
$connection->write("GET / HTTP/1.0\r\nHost: www.google.com\r\n\r\n");
...
});
$loop->run();
See also the second example.
Pending connection attempts can be cancelled by cancelling its pending promise like so:
$promise = $secureConnector->connect('www.google.com:443');
$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 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 aTcpConnector
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.
The TimeoutConnector
class implements the
ConnectorInterface
and allows you to add timeout
handling to any existing connector instance.
It does so by decorating any given 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->connect('google.com:80')->then(function (ConnectionInterface $connection) {
// connection succeeded within 3.0 seconds
});
See also any of the examples.
Pending connection attempts can be cancelled by cancelling its pending promise like so:
$promise = $timeoutConnector->connect('google.com:80');
$promise->cancel();
Calling cancel()
on a pending promise will cancel the underlying connection
attempt, abort the timer and reject the resulting promise.
The UnixConnector
class implements the
ConnectorInterface
and allows you to connect to
Unix domain socket (UDS) paths like this:
$connector = new React\SocketClient\UnixConnector($loop);
$connector->connect('/tmp/demo.sock')->then(function (ConnectionInterface $connection) {
$connection->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.
The recommended way to install this library is through Composer. New to Composer?
This will install the latest supported version:
$ composer require react/socket-client:^0.6
More details about version upgrades can be found in the CHANGELOG.
To run the test suite, you first need to clone this repo and then install all dependencies through Composer:
$ composer install
To run the test suite, go to the project root and run:
$ php vendor/bin/phpunit
MIT, see LICENSE file.