Giter Club home page Giter Club logo

socket's Introduction

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 used to pause accepting new incoming connections.

Removes the socket resource from the EventLoop and thus stop accepting new connections. Note that the listening socket stays active and is not closed.

This means that new incoming connections will stay pending in the operating system backlog until its configurable backlog is filled. Once the backlog is filled, the operating system may reject further incoming connections until the backlog is drained again by resuming to accept new connections.

Once the server is paused, no futher connection events SHOULD be emitted.

$socket->pause();

$socket->on('connection', assertShouldNeverCalled());

This method is advisory-only, though generally not recommended, the server MAY continue emitting connection events.

Unless otherwise noted, a successfully opened server SHOULD NOT start in paused state.

You can continue processing events by calling resume() again.

Note that both methods can be called any number of times, in particular calling pause() more than once SHOULD NOT have any effect. Similarly, calling this after close() is a NO-OP.

resume()

The resume(): void method can be used to resume accepting new incoming connections.

Re-attach the socket resource to the EventLoop after a previous pause().

$socket->pause();

Loop::addTimer(1.0, function () use ($socket) {
    $socket->resume();
});

Note that both methods can be called any number of times, in particular calling resume() without a prior pause() SHOULD NOT have any effect. Similarly, calling this after close() is a NO-OP.

close()

The close(): void method can be used to shut down this listening socket.

This will stop listening for new incoming connections on this socket.

echo 'Shutting down server socket' . PHP_EOL;
$socket->close();

Calling this method more than once on the same instance is a NO-OP.

SocketServer

The SocketServer class is the main class in this package that implements the ServerInterface and allows you to accept incoming streaming connections, such as plaintext TCP/IP or secure TLS connection streams.

In order to accept plaintext TCP/IP connections, you can simply pass a host and port combination like this:

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

Listening on the localhost address 127.0.0.1 means it will not be reachable from outside of this system. In order to change the host the socket is listening on, you can provide an IP address of an interface or use the special 0.0.0.0 address to listen on all interfaces:

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

If you want to listen on an IPv6 address, you MUST enclose the host in square brackets:

$socket = new React\Socket\SocketServer('[::1]:8080');

In order to use a random port assignment, you can use the port 0:

$socket = new React\Socket\SocketServer('127.0.0.1:0');
$address = $socket->getAddress();

To listen on a Unix domain socket (UDS) path, you MUST prefix the URI with the unix:// scheme:

$socket = new React\Socket\SocketServer('unix:///tmp/server.sock');

In order to listen on an existing file descriptor (FD) number, you MUST prefix the URI with php://fd/ like this:

$socket = new React\Socket\SocketServer('php://fd/3');

If the given URI is invalid, does not contain a port, any other scheme or if it contains a hostname, it will throw an InvalidArgumentException:

// throws InvalidArgumentException due to missing port
$socket = new React\Socket\SocketServer('127.0.0.1');

If the given URI appears to be valid, but listening on it fails (such as if port is already in use or port below 1024 may require root access etc.), it will throw a RuntimeException:

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

// throws RuntimeException because port is already in use
$second = new React\Socket\SocketServer('127.0.0.1:8080');

Note that these error conditions may vary depending on your system and/or configuration. See the exception message and code for more details about the actual error condition.

Optionally, you can specify TCP socket context options for the underlying stream socket resource like this:

$socket = new React\Socket\SocketServer('[::1]:8080', array(
    'tcp' => array(
        'backlog' => 200,
        'so_reuseport' => true,
        'ipv6_v6only' => true
    )
));

Note that available socket context options, their defaults and effects of changing these may vary depending on your system and/or PHP version. Passing unknown context options has no effect. The backlog context option defaults to 511 unless given explicitly.

You can start a secure TLS (formerly known as SSL) server by simply prepending the tls:// URI scheme. Internally, it will wait for plaintext TCP/IP connections and then performs a TLS handshake for each connection. It thus requires valid TLS context options, which in its most basic form may look something like this if you're using a PEM encoded certificate file:

$socket = new React\Socket\SocketServer('tls://127.0.0.1:8080', array(
    'tls' => array(
        'local_cert' => 'server.pem'
    )
));

Note that the certificate file will not be loaded on instantiation but when an incoming connection initializes its TLS context. This implies that any invalid certificate file paths or contents will only cause an error event at a later time.

If your private key is encrypted with a passphrase, you have to specify it like this:

$socket = new React\Socket\SocketServer('tls://127.0.0.1:8000', array(
    'tls' => array(
        'local_cert' => 'server.pem',
        'passphrase' => 'secret'
    )
));

By default, this server supports TLSv1.0+ and excludes support for legacy SSLv2/SSLv3. As of PHP 5.6+ you can also explicitly choose the TLS version you want to negotiate with the remote side:

$socket = new React\Socket\SocketServer('tls://127.0.0.1:8000', array(
    'tls' => array(
        'local_cert' => 'server.pem',
        'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_2_SERVER
    )
));

Note that available TLS context options, their defaults and effects of changing these may vary depending on your system and/or PHP version. The outer context array allows you to also use tcp (and possibly more) context options at the same time. Passing unknown context options has no effect. If you do not use the tls:// scheme, then passing tls context options has no effect.

Whenever a client connects, it will emit a connection event with a connection instance implementing ConnectionInterface:

$socket->on('connection', function (React\Socket\ConnectionInterface $connection) {
    echo 'Plaintext connection from ' . $connection->getRemoteAddress() . PHP_EOL;
    
    $connection->write('hello there!' . PHP_EOL);
    …
});

See also the ServerInterface for more details.

This class takes an optional LoopInterface|null $loop parameter that can be used to pass the event loop instance to use for this object. You can use a null value here in order to use the default loop. This value SHOULD NOT be given unless you're sure you want to explicitly use a given event loop instance.

Note that the SocketServer class is a concrete implementation for TCP/IP sockets. If you want to typehint in your higher-level protocol implementation, you SHOULD use the generic ServerInterface instead.

Changelog v1.9.0: This class has been added with an improved constructor signature as a replacement for the previous Server class in order to avoid any ambiguities. The previous name has been deprecated and should not be used anymore.

Advanced server usage

TcpServer

The TcpServer class implements the ServerInterface and is responsible for accepting plaintext TCP/IP connections.

$server = new React\Socket\TcpServer(8080);

As above, the $uri parameter can consist of only a port, in which case the server will default to listening on the localhost address 127.0.0.1, which means it will not be reachable from outside of this system.

In order to use a random port assignment, you can use the port 0:

$server = new React\Socket\TcpServer(0);
$address = $server->getAddress();

In order to change the host the socket is listening on, you can provide an IP address through the first parameter provided to the constructor, optionally preceded by the tcp:// scheme:

$server = new React\Socket\TcpServer('192.168.0.1:8080');

If you want to listen on an IPv6 address, you MUST enclose the host in square brackets:

$server = new React\Socket\TcpServer('[::1]:8080');

If the given URI is invalid, does not contain a port, any other scheme or if it contains a hostname, it will throw an InvalidArgumentException:

// throws InvalidArgumentException due to missing port
$server = new React\Socket\TcpServer('127.0.0.1');

If the given URI appears to be valid, but listening on it fails (such as if port is already in use or port below 1024 may require root access etc.), it will throw a RuntimeException:

$first = new React\Socket\TcpServer(8080);

// throws RuntimeException because port is already in use
$second = new React\Socket\TcpServer(8080);

Note that these error conditions may vary depending on your system and/or configuration. See the exception message and code for more details about the actual error condition.

This class takes an optional LoopInterface|null $loop parameter that can be used to pass the event loop instance to use for this object. You can use a null value here in order to use the default loop. This value SHOULD NOT be given unless you're sure you want to explicitly use a given event loop instance.

Optionally, you can specify socket context options for the underlying stream socket resource like this:

$server = new React\Socket\TcpServer('[::1]:8080', null, array(
    'backlog' => 200,
    'so_reuseport' => true,
    'ipv6_v6only' => true
));

Note that available socket context options, their defaults and effects of changing these may vary depending on your system and/or PHP version. Passing unknown context options has no effect. The backlog context option defaults to 511 unless given explicitly.

Whenever a client connects, it will emit a connection event with a connection instance implementing ConnectionInterface:

$server->on('connection', function (React\Socket\ConnectionInterface $connection) {
    echo 'Plaintext connection from ' . $connection->getRemoteAddress() . PHP_EOL;
    
    $connection->write('hello there!' . PHP_EOL);
    …
});

See also the ServerInterface for more details.

SecureServer

The SecureServer class implements the ServerInterface and is responsible for providing a secure TLS (formerly known as SSL) server.

It does so by wrapping a TcpServer instance which waits for plaintext TCP/IP connections and then performs a TLS handshake for each connection. It thus requires valid TLS context options, which in its most basic form may look something like this if you're using a PEM encoded certificate file:

$server = new React\Socket\TcpServer(8000);
$server = new React\Socket\SecureServer($server, null, array(
    'local_cert' => 'server.pem'
));

Note that the certificate file will not be loaded on instantiation but when an incoming connection initializes its TLS context. This implies that any invalid certificate file paths or contents will only cause an error event at a later time.

If your private key is encrypted with a passphrase, you have to specify it like this:

$server = new React\Socket\TcpServer(8000);
$server = new React\Socket\SecureServer($server, null, array(
    'local_cert' => 'server.pem',
    'passphrase' => 'secret'
));

By default, this server supports TLSv1.0+ and excludes support for legacy SSLv2/SSLv3. As of PHP 5.6+ you can also explicitly choose the TLS version you want to negotiate with the remote side:

$server = new React\Socket\TcpServer(8000);
$server = new React\Socket\SecureServer($server, null, array(
    'local_cert' => 'server.pem',
    'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_2_SERVER
));

Note that available TLS context options, their defaults and effects of changing these may vary depending on your system and/or PHP version. Passing unknown context options has no effect.

Whenever a client completes the TLS handshake, it will emit a connection event with a connection instance implementing ConnectionInterface:

$server->on('connection', function (React\Socket\ConnectionInterface $connection) {
    echo 'Secure connection from' . $connection->getRemoteAddress() . PHP_EOL;
    
    $connection->write('hello there!' . PHP_EOL);
    …
});

Whenever a client fails to perform a successful TLS handshake, it will emit an error event and then close the underlying TCP/IP connection:

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

See also the ServerInterface for more details.

Note that the SecureServer class is a concrete implementation for TLS sockets. If you want to typehint in your higher-level protocol implementation, you SHOULD use the generic ServerInterface instead.

This class takes an optional LoopInterface|null $loop parameter that can be used to pass the event loop instance to use for this object. You can use a null value here in order to use the default loop. This value SHOULD NOT be given unless you're sure you want to explicitly use a given event loop instance.

Advanced usage: Despite allowing any ServerInterface as first parameter, you SHOULD pass a TcpServer instance as first parameter, unless you know what you're doing. Internally, the SecureServer has to set the required TLS context options on the underlying stream resources. These resources are not exposed through any of the interfaces defined in this package, but only through the internal Connection class. The TcpServer class is guaranteed to emit connections that implement the ConnectionInterface and uses the internal Connection class in order to expose these underlying resources. If you use a custom ServerInterface and its connection event does not meet this requirement, the SecureServer will emit an error event and then close the underlying connection.

UnixServer

The UnixServer class implements the ServerInterface and is responsible for accepting connections on Unix domain sockets (UDS).

$server = new React\Socket\UnixServer('/tmp/server.sock');

As above, the $uri parameter can consist of only a socket path or socket path prefixed by the unix:// scheme.

If the given URI appears to be valid, but listening on it fails (such as if the socket is already in use or the file not accessible etc.), it will throw a RuntimeException:

$first = new React\Socket\UnixServer('/tmp/same.sock');

// throws RuntimeException because socket is already in use
$second = new React\Socket\UnixServer('/tmp/same.sock');

Note that these error conditions may vary depending on your system and/or configuration. In particular, Zend PHP does only report "Unknown error" when the UDS path already exists and can not be bound. You may want to check is_file() on the given UDS path to report a more user-friendly error message in this case. See the exception message and code for more details about the actual error condition.

This class takes an optional LoopInterface|null $loop parameter that can be used to pass the event loop instance to use for this object. You can use a null value here in order to use the default loop. This value SHOULD NOT be given unless you're sure you want to explicitly use a given event loop instance.

Whenever a client connects, it will emit a connection event with a connection instance implementing ConnectionInterface:

$server->on('connection', function (React\Socket\ConnectionInterface $connection) {
    echo 'New connection' . PHP_EOL;

    $connection->write('hello there!' . PHP_EOL);
    …
});

See also the ServerInterface for more details.

LimitingServer

The LimitingServer decorator wraps a given ServerInterface and is responsible for limiting and keeping track of open connections to this server instance.

Whenever the underlying server emits a connection event, it will check its limits and then either

  • keep track of this connection by adding it to the list of open connections and then forward the connection event
  • or reject (close) the connection when its limits are exceeded and will forward an error event instead.

Whenever a connection closes, it will remove this connection from the list of open connections.

$server = new React\Socket\LimitingServer($server, 100);
$server->on('connection', function (React\Socket\ConnectionInterface $connection) {
    $connection->write('hello there!' . PHP_EOL);
    …
});

See also the second example for more details.

You have to pass a maximum number of open connections to ensure the server will automatically reject (close) connections once this limit is exceeded. In this case, it will emit an error event to inform about this and no connection event will be emitted.

$server = new React\Socket\LimitingServer($server, 100);
$server->on('connection', function (React\Socket\ConnectionInterface $connection) {
    $connection->write('hello there!' . PHP_EOL);
    …
});

You MAY pass a null limit in order to put no limit on the number of open connections and keep accepting new connection until you run out of operating system resources (such as open file handles). This may be useful if you do not want to take care of applying a limit but still want to use the getConnections() method.

You can optionally configure the server to pause accepting new connections once the connection limit is reached. In this case, it will pause the underlying server and no longer process any new connections at all, thus also no longer closing any excessive connections. The underlying operating system is responsible for keeping a backlog of pending connections until its limit is reached, at which point it will start rejecting further connections. Once the server is below the connection limit, it will continue consuming connections from the backlog and will process any outstanding data on each connection. This mode may be useful for some protocols that are designed to wait for a response message (such as HTTP), but may be less useful for other protocols that demand immediate responses (such as a "welcome" message in an interactive chat).

$server = new React\Socket\LimitingServer($server, 100, true);
$server->on('connection', function (React\Socket\ConnectionInterface $connection) {
    $connection->write('hello there!' . PHP_EOL);
    …
});
getConnections()

The getConnections(): ConnectionInterface[] method can be used to return an array with all currently active connections.

foreach ($server->getConnection() as $connection) {
    $connection->write('Hi!');
}

Client usage

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:

connect()

The connect(string $uri): PromiseInterface<ConnectionInterface> 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 (React\Socket\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();

Connector

The Connector class is the main class in this package that implements the ConnectorInterface and allows you to create streaming connections.

You can use this connector to create any kind of streaming connections, such as plaintext TCP/IP, secure TLS or local Unix connection streams.

It binds to the main event loop and can be used like this:

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

$connector->connect($uri)->then(function (React\Socket\ConnectionInterface $connection) {
    $connection->write('...');
    $connection->end();
}, function (Exception $e) {
    echo 'Error: ' . $e->getMessage() . PHP_EOL;
});

In order to create a plaintext TCP/IP connection, you can simply pass a host and port combination like this:

$connector->connect('www.google.com:80')->then(function (React\Socket\ConnectionInterface $connection) {
    $connection->write('...');
    $connection->end();
});

If you do no specify a URI scheme in the destination URI, it will assume tcp:// as a default and establish a plaintext TCP/IP connection. Note that TCP/IP connections require a host and port part in the destination URI like above, all other URI components are optional.

In order to create a secure TLS connection, you can use the tls:// URI scheme like this:

$connector->connect('tls://www.google.com:443')->then(function (React\Socket\ConnectionInterface $connection) {
    $connection->write('...');
    $connection->end();
});

In order to create a local Unix domain socket connection, you can use the unix:// URI scheme like this:

$connector->connect('unix:///tmp/demo.sock')->then(function (React\Socket\ConnectionInterface $connection) {
    $connection->write('...');
    $connection->end();
});

The getRemoteAddress() method will return the target Unix domain socket (UDS) path as given to the connect() method, including the unix:// scheme, for example unix:///tmp/demo.sock. The getLocalAddress() method will most likely return a null value as this value is not applicable to UDS connections here.

Under the hood, the Connector is implemented as a higher-level facade for the lower-level connectors implemented in this package. This means it also shares all of their features and implementation details. If you want to typehint in your higher-level protocol implementation, you SHOULD use the generic ConnectorInterface instead.

As of v1.4.0, the Connector class defaults to using the happy eyeballs algorithm to automatically connect over IPv4 or IPv6 when a hostname is given. This automatically attempts to connect using both IPv4 and IPv6 at the same time (preferring IPv6), thus avoiding the usual problems faced by users with imperfect IPv6 connections or setups. If you want to revert to the old behavior of only doing an IPv4 lookup and only attempt a single IPv4 connection, you can set up the Connector like this:

$connector = new React\Socket\Connector(array(
    'happy_eyeballs' => false
));

Similarly, you can also affect the default DNS behavior as follows. The Connector class will try to detect your system DNS settings (and uses Google's public DNS server 8.8.8.8 as a fallback if unable to determine your system settings) to resolve all public hostnames into underlying IP addresses by default. If you explicitly want to use a custom DNS server (such as a local DNS relay or a company wide DNS server), you can set up the Connector like this:

$connector = new React\Socket\Connector(array(
    'dns' => '127.0.1.1'
));

$connector->connect('localhost:80')->then(function (React\Socket\ConnectionInterface $connection) {
    $connection->write('...');
    $connection->end();
});

If you do not want to use a DNS resolver at all and want to connect to IP addresses only, you can also set up your Connector like this:

$connector = new React\Socket\Connector(array(
    'dns' => false
));

$connector->connect('127.0.0.1:80')->then(function (React\Socket\ConnectionInterface $connection) {
    $connection->write('...');
    $connection->end();
});

Advanced: If you need a custom DNS React\Dns\Resolver\ResolverInterface instance, you can also set up your Connector like this:

$dnsResolverFactory = new React\Dns\Resolver\Factory();
$resolver = $dnsResolverFactory->createCached('127.0.1.1');

$connector = new React\Socket\Connector(array(
    'dns' => $resolver
));

$connector->connect('localhost:80')->then(function (React\Socket\ConnectionInterface $connection) {
    $connection->write('...');
    $connection->end();
});

By default, the tcp:// and tls:// URI schemes will use timeout value that respects your default_socket_timeout ini setting (which defaults to 60s). If you want a custom timeout value, you can simply pass this like this:

$connector = new React\Socket\Connector(array(
    'timeout' => 10.0
));

Similarly, if you do not want to apply a timeout at all and let the operating system handle this, you can pass a boolean flag like this:

$connector = new React\Socket\Connector(array(
    'timeout' => false
));

By default, the Connector supports the tcp://, tls:// and unix:// URI schemes. If you want to explicitly prohibit any of these, you can simply pass boolean flags like this:

// only allow secure TLS connections
$connector = new React\Socket\Connector(array(
    'tcp' => false,
    'tls' => true,
    'unix' => false,
));

$connector->connect('tls://google.com:443')->then(function (React\Socket\ConnectionInterface $connection) {
    $connection->write('...');
    $connection->end();
});

The tcp:// and tls:// also accept additional context options passed to the underlying connectors. If you want to explicitly pass additional context options, you can simply pass arrays of context options like this:

// allow insecure TLS connections
$connector = new React\Socket\Connector(array(
    'tcp' => array(
        'bindto' => '192.168.0.1:0'
    ),
    'tls' => array(
        'verify_peer' => false,
        'verify_peer_name' => false
    ),
));

$connector->connect('tls://localhost:443')->then(function (React\Socket\ConnectionInterface $connection) {
    $connection->write('...');
    $connection->end();
});

By default, this connector supports TLSv1.0+ and excludes support for legacy SSLv2/SSLv3. As of PHP 5.6+ you can also explicitly choose the TLS version you want to negotiate with the remote side:

$connector = new React\Socket\Connector(array(
    'tls' => array(
        'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
    )
));

For more details about context options, please refer to the PHP documentation about socket context options and SSL context options.

Advanced: By default, the Connector supports the tcp://, tls:// and unix:// URI schemes. For this, it sets up the required connector classes automatically. If you want to explicitly pass custom connectors for any of these, you can simply pass an instance implementing the ConnectorInterface like this:

$dnsResolverFactory = new React\Dns\Resolver\Factory();
$resolver = $dnsResolverFactory->createCached('127.0.1.1');
$tcp = new React\Socket\HappyEyeBallsConnector(null, new React\Socket\TcpConnector(), $resolver);

$tls = new React\Socket\SecureConnector($tcp);

$unix = new React\Socket\UnixConnector();

$connector = new React\Socket\Connector(array(
    'tcp' => $tcp,
    'tls' => $tls,
    'unix' => $unix,

    'dns' => false,
    'timeout' => false,
));

$connector->connect('google.com:80')->then(function (React\Socket\ConnectionInterface $connection) {
    $connection->write('...');
    $connection->end();
});

Internally, the tcp:// connector will always be wrapped by the DNS resolver, unless you disable DNS like in the above example. In this case, the tcp:// connector receives the actual hostname instead of only the resolved IP address and is thus responsible for performing the lookup. Internally, the automatically created tls:// connector will always wrap the underlying tcp:// connector for establishing the underlying plaintext TCP/IP connection before enabling secure TLS mode. If you want to use a custom underlying tcp:// connector for secure TLS connections only, you may explicitly pass a tls:// connector like above instead. Internally, the tcp:// and tls:// connectors will always be wrapped by TimeoutConnector, unless you disable timeouts like in the above example.

This class takes an optional LoopInterface|null $loop parameter that can be used to pass the event loop instance to use for this object. You can use a null value here in order to use the default loop. This value SHOULD NOT be given unless you're sure you want to explicitly use a given event loop instance.

Changelog v1.9.0: The constructur signature has been updated to take the optional $context as the first parameter and the optional $loop as a second argument. The previous signature has been deprecated and should not be used anymore.

// constructor signature as of v1.9.0
$connector = new React\Socket\Connector(array $context = [], ?LoopInterface $loop = null);

// legacy constructor signature before v1.9.0
$connector = new React\Socket\Connector(?LoopInterface $loop = null, array $context = []);

Advanced client usage

TcpConnector

The TcpConnector class implements the ConnectorInterface and allows you to create plaintext TCP/IP connections to any IP-port-combination:

$tcpConnector = new React\Socket\TcpConnector();

$tcpConnector->connect('127.0.0.1:80')->then(function (React\Socket\ConnectionInterface $connection) {
    $connection->write('...');
    $connection->end();
});

See also the examples.

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.

This class takes an optional LoopInterface|null $loop parameter that can be used to pass the event loop instance to use for this object. You can use a null value here in order to use the default loop. This value SHOULD NOT be given unless you're sure you want to explicitly use a given event loop instance.

You can optionally pass additional socket context options to the constructor like this:

$tcpConnector = new React\Socket\TcpConnector(null, array(
    'bindto' => '192.168.0.1:0'
));

Note that this class only allows you to connect to IP-port-combinations. If the given URI is invalid, does not contain a valid IP address and port or contains any other scheme, it will reject with an InvalidArgumentException:

If the given URI appears to be valid, but connecting to it fails (such as if the remote host rejects the connection etc.), it will reject with a RuntimeException.

If you want to connect to hostname-port-combinations, see also the following chapter.

Advanced usage: Internally, the TcpConnector allocates an empty context resource for each stream resource. If the destination URI contains a hostname query parameter, its value will be used to set up the TLS peer name. This is used by the SecureConnector and DnsConnector to verify the peer name and can also be used if you want a custom TLS peer name.

HappyEyeBallsConnector

The HappyEyeBallsConnector class implements the ConnectorInterface and allows you to create plaintext TCP/IP connections to any hostname-port-combination. Internally it implements the happy eyeballs algorithm from RFC6555 and RFC8305 to support IPv6 and IPv4 hostnames.

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');

$dnsConnector = new React\Socket\HappyEyeBallsConnector(null, $tcpConnector, $dns);

$dnsConnector->connect('www.google.com:80')->then(function (React\Socket\ConnectionInterface $connection) {
    $connection->write('...');
    $connection->end();
});

See also the examples.

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 lookups and/or the underlying TCP/IP connection(s) and reject the resulting promise.

This class takes an optional LoopInterface|null $loop parameter that can be used to pass the event loop instance to use for this object. You can use a null value here in order to use the default loop. This value SHOULD NOT be given unless you're sure you want to explicitly use a given event loop instance.

Advanced usage: Internally, the HappyEyeBallsConnector relies on a Resolver to look up the IP addresses for the given hostname. It will then replace the hostname in the destination URI with this IP's and append a hostname query parameter and pass this updated URI to the underlying connector. The Happy Eye Balls algorithm describes looking the IPv6 and IPv4 address for the given hostname so this connector sends out two DNS lookups for the A and AAAA records. It then uses all IP addresses (both v6 and v4) and tries to connect to all of them with a 50ms interval in between. Alterating between IPv6 and IPv4 addresses. When a connection is established all the other DNS lookups and connection attempts are cancelled.

DnsConnector

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->createCached('8.8.8.8');

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

$dnsConnector->connect('www.google.com:80')->then(function (React\Socket\ConnectionInterface $connection) {
    $connection->write('...');
    $connection->end();
});

See also the examples.

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.

Advanced usage: Internally, the DnsConnector relies on a React\Dns\Resolver\ResolverInterface to look up the IP address for the given hostname. It will then replace the hostname in the destination URI with this IP and append a hostname query parameter and pass this updated URI to the underlying connector. The underlying connector is thus responsible for creating a connection to the target IP address, while this query parameter can be used to check the original hostname and is used by the TcpConnector to set up the TLS peer name. If a hostname is given explicitly, this query parameter will not be modified, which can be useful if you want a custom TLS peer name.

SecureConnector

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\Socket\SecureConnector($dnsConnector);

$secureConnector->connect('www.google.com:443')->then(function (React\Socket\ConnectionInterface $connection) {
    $connection->write("GET / HTTP/1.0\r\nHost: www.google.com\r\n\r\n");
    ...
});

See also the examples.

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 negotiation and reject the resulting promise.

This class takes an optional LoopInterface|null $loop parameter that can be used to pass the event loop instance to use for this object. You can use a null value here in order to use the default loop. This value SHOULD NOT be given unless you're sure you want to explicitly use a given event loop instance.

You can optionally pass additional SSL context options to the constructor like this:

$secureConnector = new React\Socket\SecureConnector($dnsConnector, null, array(
    'verify_peer' => false,
    'verify_peer_name' => false
));

By default, this connector supports TLSv1.0+ and excludes support for legacy SSLv2/SSLv3. As of PHP 5.6+ you can also explicitly choose the TLS version you want to negotiate with the remote side:

$secureConnector = new React\Socket\SecureConnector($dnsConnector, null, array(
    'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
));

Advanced usage: Internally, the SecureConnector relies on setting up 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 and verify the peer name. Failing to do so may result in a TLS peer name mismatch error or some hard to trace race conditions, because all stream resources will use a single, shared default context resource otherwise.

TimeoutConnector

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\Socket\TimeoutConnector($connector, 3.0);

$timeoutConnector->connect('google.com:80')->then(function (React\Socket\ConnectionInterface $connection) {
    // connection succeeded within 3.0 seconds
});

See also any of the examples.

This class takes an optional LoopInterface|null $loop parameter that can be used to pass the event loop instance to use for this object. You can use a null value here in order to use the default loop. This value SHOULD NOT be given unless you're sure you want to explicitly use a given event loop instance.

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.

UnixConnector

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

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

$connector->connect('/tmp/demo.sock')->then(function (React\Socket\ConnectionInterface $connection) {
    $connection->write("HELLO\n");
});

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 getRemoteAddress() method will return the target Unix domain socket (UDS) path as given to the connect() method, prepended with the unix:// scheme, for example unix:///tmp/demo.sock. The getLocalAddress() method will most likely return a null value as this value is not applicable to UDS connections here.

This class takes an optional LoopInterface|null $loop parameter that can be used to pass the event loop instance to use for this object. You can use a null value here in order to use the default loop. This value SHOULD NOT be given unless you're sure you want to explicitly use a given event loop instance.

FixedUriConnector

The FixedUriConnector class implements the ConnectorInterface and decorates an existing Connector to always use a fixed, preconfigured URI.

This can be useful for consumers that do not support certain URIs, such as when you want to explicitly connect to a Unix domain socket (UDS) path instead of connecting to a default address assumed by an higher-level API:

$connector = new React\Socket\FixedUriConnector(
    'unix:///var/run/docker.sock',
    new React\Socket\UnixConnector()
);

// destination will be ignored, actually connects to Unix domain socket
$promise = $connector->connect('localhost:80');

Install

The recommended way to install this library is through Composer. New to Composer?

Once released, this project will follow SemVer. At the moment, this will install the latest development version:

composer require react/socket:^3@dev

See also the CHANGELOG for details about version upgrades.

This project aims to run on any platform and thus does not require any PHP extensions and supports running on legacy PHP 5.3 through current PHP 8+ and HHVM. It's highly recommended to use the latest supported PHP version for this project, partly due to its vast performance improvements and partly because legacy PHP versions require several workarounds as described below.

Secure TLS connections received some major upgrades starting with PHP 5.6, with the defaults now being more secure, while older versions required explicit context options. This library does not take responsibility over these context options, so it's up to consumers of this library to take care of setting appropriate context options as described above.

PHP < 7.3.3 (and PHP < 7.2.15) suffers from a bug where feof() might block with 100% CPU usage on fragmented TLS records. We try to work around this by always consuming the complete receive buffer at once to avoid stale data in TLS buffers. This is known to work around high CPU usage for well-behaving peers, but this may cause very large data chunks for high throughput scenarios. The buggy behavior can still be triggered due to network I/O buffers or malicious peers on affected versions, upgrading is highly recommended.

PHP < 7.1.4 (and PHP < 7.0.18) suffers from a bug when writing big chunks of data over TLS streams at once. We try to work around this by limiting the write chunk size to 8192 bytes for older PHP versions only. This is only a work-around and has a noticable performance penalty on affected versions.

This project also supports running on HHVM. Note that really old HHVM < 3.8 does not support secure TLS connections, as it lacks the required stream_socket_enable_crypto() function. As such, trying to create a secure TLS connections on affected versions will return a rejected promise instead. This issue is also covered by our test suite, which will skip related tests on affected versions.

Tests

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:

vendor/bin/phpunit

The test suite also contains a number of functional integration tests that rely on a stable internet connection. If you do not want to run these, they can simply be skipped like this:

vendor/bin/phpunit --exclude-group internet

License

MIT, see LICENSE file.

socket's People

Contributors

alexmace avatar andig avatar carusogabriel avatar cboden avatar christiaan avatar clue avatar cn007b avatar daverandom avatar e3betht avatar elliot avatar hansott avatar igorw avatar jsor avatar kelunik avatar mmoreram avatar nhedger avatar reedy avatar robinvdvleuten avatar sgoettschkes avatar simonfrings avatar the-eater avatar tkleinhakisa avatar valga avatar wyrihaximus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

socket's Issues

Making $loop protected in Socket\Server and custom Connection classes?

The issue/scenario is that I would like to create a custom Connection and I am wondering what is the best way of doing it.

There are two possible ways that I can think of:

  • Allow extending Server by changing scope of $loop to protected.
  • Add a factory (like) connection class property in Server

Details for both approaches below, but first is there any reason for keeping $loop private in React\Socket\Server?

Approach 1 - changing scope of $loop to protected:
Changing scope to protected, then extending it via MyCustomServer in which I can override createConnection.

This approach is demonstrated below.

/** @event connection */
class Server extends EventEmitter implements ServerInterface
{
    public $master;
    protected $loop;    // changing scope from private to protected
    ....
}

/** MY Custom Server Class */
class MyCustomServer extends Server 
{
    public function createConnection($socket)
    {
        return new CustomConnection($socket, $this->loop);
    }
}

Approach 2 - Connection class property
Have a factory (sort of) way of creating a connection, in which a Server's property can be overwritten to create a connection e.g.

/** @event connection */
class Server extends EventEmitter implements ServerInterface
{
    public $master;
    private $loop;
    public $connectionClass = 'Connection';
    ....

    public function createConnection($socket)
    {
        return new $connectionClass($socket, $this->loop);
    }
}

Removed `full-drain` event from Buffer

Hello. I have a small problem after upgrade to latest version of reactphp/socket an event on buffer is missing. In previous version there was event full-drain. I use this event to fire handlers after data are completly sent to stream.

So is there some other way how to listen on simillar event? Right now i have patched actual buffer class React\Stream\Buffer:


    public function handleWrite()
    {
        $error = null;
        set_error_handler(function ($errno, $errstr, $errfile, $errline) use (&$error) {
            $error = array(
                'message' => $errstr,
                'number' => $errno,
                'file' => $errfile,
                'line' => $errline
            );
        });

        $sent = fwrite($this->stream, $this->data);

        restore_error_handler();

        // Only report errors if *nothing* could be sent.
        // Any hard (permanent) error will fail to send any data at all.
        // Sending excessive amounts of data will only flush *some* data and then
        // report a temporary error (EAGAIN) which we do not raise here in order
        // to keep the stream open for further tries to write.
        // Should this turn out to be a permanent error later, it will eventually
        // send *nothing* and we can detect this.
        if ($sent === 0 || $sent === false) {
            if ($error === null) {
                $error = new \RuntimeException('Send failed');
            } else {
                $error = new \ErrorException(
                    $error['message'],
                    0,
                    $error['number'],
                    $error['file'],
                    $error['line']
                );
            }

            $this->emit('error', array(new \RuntimeException('Unable to write to stream: ' . $error->getMessage(), 0, $error)));
            $this->close();

            return;
        }

        $exceeded = isset($this->data[$this->softLimit - 1]);
        $this->data = (string) substr($this->data, $sent);

        // buffer has been above limit and is now below limit
        if ($exceeded && !isset($this->data[$this->softLimit - 1])) {
            $this->emit('drain');
        }

        // buffer is now completely empty => stop trying to write
        if ($this->data === '') {
            // stop waiting for resource to be writable
            if ($this->listening) {
                $this->loop->removeWriteStream($this->stream);
                $this->listening = false;

                $this->emit('full-drain', array($this));
            }

            // buffer is end()ing and now completely empty => close buffer
            if (!$this->writable) {
                $this->close();
            }
        }
    }

added $this->emit('full-drain', array($this));

Ratchet onopen client not fire

I am trying to implement Ratchet Socket Hello word on my local machine every things works perfectly but on vps centos server when i run server service with

ssh Command : php chat-server.php
it start Listening on port correctly(i can see on linux that port is Listening ) , but when i open "clint.html" page the method onopen never fire but server says

new client connected !
and after 2 minute it says

client disconnected
if i send message to client it will take 2 minutes then client will receive it, but it will disconnect again it seems to me that there is not stable connection between server and client. every time when i check websocket.readyState its not equal to 1
i disabled firewall and any security on vps server but still have this problem. i have to mention that normal php socket functions works without problem because i could test it and every thing works http://www.abrandao.com/2013/06/websockets-html5-php/ but about ratchet it seems it hang on onopen method.

  1. port 9091 is open
  2. firewall is disabled
  3. http:://www.abrandao.com/2013/06/websockets-html5-php/ works whiteout problem and can send and receive message from clients
  4. BUT Ratchet has problem onconnect

chat-server.php
`use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat;
require dirname(DIR) . '/vendor/autoload.php';

$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
),
9091
);
echo date("Y-m-d H:i:s")." chat-server Started on port 9091 \n";
$server->run();`

Chat.php class
`namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface {
protected $clients;

public function __construct() {
$this->clients = new \SplObjectStorage;
}

public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
echo date("Y-m-d H:i:s")." New connection! ({$conn->resourceId})\n";
$conn->send("Hello {$conn->resourceId} from server at : ".date("Y-m-d H:i:s"));
echo date("Y-m-d H:i:s")." Hello Sent to ({$conn->resourceId})\n";

}

public function onMessage(ConnectionInterface $from, $msg) {
$numRecv = count($this->clients) - 1;
echo sprintf(date("Y-m-d H:i:s").'Connection %d sending message "%s" to %d other connection%s' . "\n"
, $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');
foreach ($this->clients as $client) {
if ($from !== $client) {
$client->send($msg);
}
}
}

public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
echo date("Y-m-d H:i:s")." Connection {$conn->resourceId} has disconnected\n";
}

public function onError(ConnectionInterface $conn, \Exception $e) {
echo date("Y-m-d H:i:s")." An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}`

client.html :
`$(document).ready(function(){
connect();
});

var wsUri = "ws://myserverdomain.comOrIP:9091";

function connect() {
var ws = new WebSocket(wsUri);

ws.onopen = function() {
var now = new Date();
console.log(now + ' Connected to '+wsUri);
};

ws.onmessage = function(e) {
var now = new Date();
console.log(now + ' Message Recived From Server :', e.data);
};

ws.onclose = function(e) {
var now = new Date();
console.log(now +' Socket is closed. Reconnect will be attempted in 1 second.', e.reason);
setTimeout(function() {
connect();
}, 1000)
};

ws.onerror = function(err) {
var now = new Date();
console.error(now + ' Socket encountered error: ', err.message, 'Closing socket')
console.error(err)
ws.close()
};
} `

Cannot bind IPv6 [::] (any)

        $loop = \React\EventLoop\Factory::create();
        $ip4 = new \React\Socket\Server($loop);
        $ip6 = new \React\Socket\Server($loop);
        $ip4->listen(9988, '0.0.0.0');
        $ip6->listen(9988, '::');

        $wsStack = new \Ratchet\Http\HttpServer(
            new WsServer(
                new Online()
            )
        );

        $ip4App = new IoServer($wsStack, $ip4, $loop);
        $ip6App = new IoServer($wsStack, $ip6, $loop);
        $loop->run();

This fails with:
Exception 'React\Socket\ConnectionException' with message 'Could not bind to tcp://[::]:9988: Address already in use'

But address is not in use, in fact if I replace :: with the actual machine public IPv6 address works fine.

Extend ConnectionInterface with ports / target address.

(Related to #26)

I'm implementing the proxy protocol for react:
http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt

Even though not all transports have a separate port part, I think it would be nice to add some more methods to the connection interface:

public function getTargetAddress();
public function getTargetPort();
public function getRemotePort();

-- Part below is about the naming of entities in the connection interface --

Also naming could possibly be reconsidered. Connections always have a direction (source and target), but the concept of local and remote does not always apply. I understand that getRemoteAddress() refers to the "other" end of the connection, but it could be more consistent when we use source and target.
When looking at it from a more abstract viewpoint:

Consider:
Client A connects to Server B to establish a Connection C
Both A and B both have an object representing C, say C_a and C_b
Using terms like remoteAddress and localAddress creates the following relation:

C_a.remoteAddress = C_b.localAddress 
and 
C_a.localAddress = C_b.remoteAddress

When multiple connections are managed, both inbound and outbound, we need to "know" where the connection came from to decide which party we are (local or remote).

Merge SocketClient component into this component

Here's the current situation:

  • This Socket component: Async, streaming plaintext TCP/IP and secure TLS socket server for ReactPHP
  • SocketClient component: Async, streaming plaintext TCP/IP and secure TLS socket client for ReactPHP

This is not exactly ideal, they share quite a bit of common code and actually have a dependency on one-another for their test suite.

Also, I believe this situation may be a bit confusing for consumers of this package. In particular our Datagram component provides both client and server side for datagram sockets (UDP).

As such, I'd vote for merging these two components into a single Socket component.

Error when sending large chunks of data over a secure TLS connection with older PHP versions

Originally reported here: reactphp/stream#64

This can actually easily be reproduced by sending a "large" chunk of data at once over a TLS connection. On my system, this appears to be anything larger than around 30 KB at once passed to the underlying fwrite() call.

error:1409F07F:SSL routines:SSL3_WRITE_PENDING:bad write retry

This is actually a bug in PHP that has been reported via https://bugs.php.net/bug.php?id=72333. The bug has been present for years and has been fixed recently via php/php-src@17e9fc9 which landed in 7.1.4 and 7.0.18.

I've played around with different buffers and write chunks and it looks like this can be worked around by limiting the write chunk size to anything smaller than around 8 KB.

Test failures on Mac OS X

Not really an issue, more fyi:

There were 3 failures:

1) React\Tests\Socket\FunctionalSecureServerTest::testEmitsErrorIfConnectionIsCancelled
Expectation failed for method name is equal to <string:__invoke> when invoked 1 time(s).
Method was expected to be called 1 times, actually called 0 times.

2) React\Tests\Socket\FunctionalTcpServerTest::testEmitsConnectionEvenIfConnectionIsCancelled
Expectation failed for method name is equal to <string:__invoke> when invoked 1 time(s).
Method was expected to be called 1 times, actually called 0 times.

3) React\Tests\Socket\UnixConnectorTest::testValid
Failed asserting that Binary String: 0x756e69783a2f2f000000000000000000000000000000 is null.

/Users/andig/Documents/htdocs/react-socket/tests/UnixConnectorTest.php:62

No post data received

Hi,

I have a problem working with reactPHP (http server)

Scenario.

Apache receiving data
PHP script sending data via post to another server through a php script with curl to the reactphp server.
ReactPHP server sometimes receive data and sometimes not.

I have verified that from the apache server the data is always posted.

What is the problem then?

Thanks!

Please take a look at this simple code:

require 'vendor/autoload.php';

$loop   = React\EventLoop\Factory::create();
$socket = new React\Socket\Server($loop);
$http   = new React\Http\Server($socket, $loop);

$http->on('request', function ($req, $res) {

print_r($req);


    $req->on('data', function($data) use ($req, $res) {

            parse_str($data,$datos);
            if(count($datos)==0)
            {

                    echo "No data \n";
            }


            $res->writeHead(200,
            array(
                    'Access-Control-Allow-Origin'=>'*',
                     'Content-Type' => 'text/plain'
             ));

            $res->end("Ok\n");
    });

});

$socket->listen(5000,10.1.45.39);
$loop->run();

Trying to listing on socket, works in some cases not in all

Hi, thanks for this project 😃.

I'm using this code from the README.md, with a small adjustment to output any data send to it.

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

    $socket = new React\Socket\Server($loop);
    $socket->on('connection', function ($conn) {
    echo "New connection " . $conn->getRemoteAddress() . "\n";


        $conn->on('data', function ($data) use ($conn) {
        echo "New msg from " . $conn->getRemoteAddress() . " msg: " . $data . "\n";
           $conn->close();
        });
    });
    $socket->listen(1337);

    $loop->run();

This works perfect if you start a netcat shell: nc localhost 6461, and type some data into it. However when I try to pipe some data to netcat e.g. echo "test" | nc localhost 6461, the connection is received (I see the new connection msg and ip address). However the data isn't received.

Is this normal behaviour or is this a bug? I'm trying to "catch" output from an existing service, which I can't change.

Thanks! (If you give me some hints where the bug is, I'll be happy to open a PR)

Type annotations misinterpreted by phpstan

When using this library in a project which uses phpstan for code analysis it gives the following error.

Call to method then() on an unknown class     
React\Socket\React\Promise\PromiseInterface. 

This happens because of the following return type @return React\Promise\PromiseInterface of ConnectorInterface#connect

Since the file is namespaced it expects all types to either be relative to the file namespace or to start with a \ if you want a fully qualified name.

Roadmap to stable v1.0.0

Let's face it, this project is stable and has been used in production for years :shipit:

However, we're currently following a v0.X.Y release scheme (http://sentimentalversioning.org/).

We should finally make this explicit and fully adhere to SemVer and release a stable v1.0.0.

To a large extend, a stable v1.0.0 helps making BC breaks more explicit and thus the whole project more reliable from a consumer perspective. This project is actively maintained and has received some major updates in the last weeks and has some major updates planned in the next weeks. Given our current versioning scheme, we'd like to ensure all anticipated BC breaks will be merged before the planned v1.0.0 release.

As such, I've set up a roadmap that enlists only the major changes for each version among with planned release dates towards a stable v1.0.0 release:

v0.5.0 ✅

  • Released 2017-02-14
  • No temporal dependence
  • URIs everywhere
  • Reduce public API

v0.5.1 ✅

  • Released 2017-03-09
  • Update stream component

v0.6.0 ✅

  • Released 2017-04-04
  • Limit connections (pause/resume server)

v0.7.0 ✅

  • Released 2017-04-10
  • Merge SocketClient into this component

v0.8.0 ✅

  • Released 2017-05-09
  • Server facade API
  • Address URIs

v1.0.0

  • Planned 2018-?
  • No new changes planned, this should merely mark the previous release as "stable"

This ticket aims to serve as a basic overview and does not contain every single change. Please also see the milestone links and the CHANGELOG for more details.

Obviously, this roadmap is subject to change and I'll try to keep it updated as we progress. In order to avoid cluttering this, please keep discussion in this ticket to a minimum and consider reaching out to us through new tickets or Twitter etc.

How to determine a message has been fully transfered

Hi,

I have created a server socket;

        $this->socket->on('connection', function(ConnectionInterface $connection){
               $connection->on('data', function($message) {
                   $this->createHandler($message, $connection)->handle($message);
               });
        });
        $this->socket->on('error', function($exception){
            $this->dispatcher->dispatch(new Event(EventStore::SOCKET_ERROR, $this, [
                'exception' => $exception
            ]));
        });
        $this->loop->run();

If a socket client send large chunks of data(greater than 65535) to the server. the listener for the event "data" will only get partial content every time.
How to gather all the partial content into a complete message?

[Client] Connector does not honor /etc/resolv.conf

The Connector is currently hard-coded to default to Google's public DNS server 8.8.8.8. You can explicitly pass a custom DNS server (or Resolver instance) like this:

$connector = new Connector($loop, array(
    'dns' => '127.0.0.1'
));

Opening this ticket as a reminder - this actually depends on reactphp/dns#29

[React/Socket/Server]: Can not create socket server #43

I'm using Fedora 26 with turned off selinux

When I try to create new instance of
new \React\Socket\Server( "127.0.0.1:5555", $loop);

[RuntimeException]
Failed to listen on "tcp://127.0.0.1:5555": Address already in use

$ sudo lsof -i tcp:5555
$

Server::createConnection breaks SRP

Shouldn't a ConnectionFactory be passed into Server::__construct instead of having a hardcoded classname in createConnection?
According to the single responsibility principle usage of an object should be separate from its construction right?

[Client] DNS should have option to use IPv6 (AAAA) records

The Connector (and underlying DnsConnector) is currently hard-coded to only look up IPv4 (A) records from the DNS server. There is currently no way to tell it to look up IPv6 (AAAA) records.

(Note that explicitly connecting to IPv4 and IPv6 addresses works just fine)

We should implement a way to explicitly define the lookup mode and eventually find a way to automatically use the correct mode (figure out if this system prefers or even supports IPv6).

Opening this ticket as a reminder and to spark the discussion - the implementation likely depends on reactphp/dns#43

header

tell me how to put in the library header?
header ('Access-Control-Allow-Origin: *');
It does not work

Async SSL/TLS server

Migrated from reactphp/reactphp#2, originally reported 2012-05-11

This ticket aims to serve as a basis for discussion whether (and how) we should provide an async SSL/TLS server.

Clean up temporal dependence

The current socket API exhibits a temporal dependence:

$server = new Server($loop);
$server->listen(1234);
$server->getPort();
$server->on('connection', function () { });
$server->shutdown();
  • What happens if you call listen() twice?
    It's tempting to think that this will allow you to listen on two addresses – it does not.
  • What happens if you call shutdown() twice or before calling listen()?
    Errors out – should probably be ignored
  • What happens if you call getPort() before calling listen() or after calling shutdown()?
    Errors out – should probably be ignored
  • What happens if you call listen() after calling shutdown()?
    Should work, but makes for an awkward API.

Afaict most of this boils down to this:

  • What does a Server instance actually represent?
    Honestly, I'm not sure how to answer this. Once listen() has been called, it represents a "server socket", but until then?

Afaict most of these issues can be avoided if a Server instance always were to represent a "server socket" (which is possibly in a closed state). This means that the listen call would have to be part of the construction.

One possible API could look like this:

$server = $api->createServer(1234);
$server->getPort();
$server->on('connection', function() { });
$server->shutdown();

No data returned from server written to socket before connection close

Hi!

I have a following code

$socket->on('connection', function ($conn) 
{
  $conn->write("Hello there!\n");

  $conn->on('data', function ($data) use ($conn) {
    $conn->write("I have received a data!\n");
    $conn->close();
  });
});

The problem is I only receive "Hello there" string, but not "I have received a data!\n". I am not receiving second string even with sleep(5) or something before $conn->close() line. Is this a bug or I am doing something wrong?

Thank you in advance.

PS

comoser:

{
    "require": {
        "react/socket": "~0.4.0"
    }
}

php -v:

PHP 7.0.5 (cli) (built: Apr  2 2016 23:10:23) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies

Looks like there are too many opened sockets... Leak?

Ref: reactphp/http#27

Versions:

$ uname -a
Linux dev.qfox.ru 3.2.0-4-486 #1 Debian 3.2.51-1 i686 GNU/Linux
$ php -v
PHP 5.4.38-1~dotdeb.1 (cli) (built: Feb 19 2015 22:21:23)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2014 Zend Technologies
    with Xdebug v2.3.1, Copyright (c) 2002-2015, by Derick Rethans

I have a simple file app.php:

require 'vendor/autoload.php';

$app = function ($request, $response) {
    $response->writeHead(200, array('Content-Type' => 'text/plain'));
    $response->end("Hello World\n");
};

$loop = React\EventLoop\Factory::create();
$socket = new React\Socket\Server($loop);
$http = new React\Http\Server($socket, $loop);

$http->on('request', $app);
echo "Server running at http://0.0.0.0:1337\n";

$socket->listen(1337, '0.0.0.0');
$loop->run();

With installed react/http (here is my composer.json):

{
    "require": {
        "react/http": "0.3.*"
    }
}

Running it:

$ php app.php
Server running at http://127.0.0.1:1337

And sending 10k requests:

$ ab -n 10000 -c 500 http://localhost:1337/
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking localhost (be patient)
Completed 1000 requests
Completed 2000 requests
Completed 3000 requests
Completed 4000 requests
Completed 5000 requests
Completed 6000 requests
Completed 7000 requests
Completed 8000 requests
Completed 9000 requests
apr_socket_recv: Connection reset by peer (104)
Total of 9953 requests completed

Why some of requests was reseted by peer? Something is wrong?

Listening on same port twice does not fail on Windows

Test suite for v0.4.4 fails on Windows, using both 5.6.29 and 7.0.13, with PHPUnit 4.8.31

PHPUnit 4.8.31 by Sebastian Bergmann and contributors.

...............F

Time: 21.31 seconds, Memory: 8.00MB

There was 1 failure:

1) React\Tests\Socket\ServerTest::testListenOnBusyPortThrows
Failed asserting that exception of type "React\Socket\ConnectionException" is thrown.

FAILURES!
Tests: 16, Assertions: 15, Failures: 1.

Edit: expanded information to include full phpunit output

Unix-style sockets - error 11, Resource temporarily unavailable

Hi guys,

If You have a moment pls look at this comment of mine. We tracked a possible issue with unix-style sockets (I merged ready pull request there). You will find there a small example to reproduce the issue.

The issue occurs when using unix socket with a lot of processes trying to connect in the same moment (starting 1 master instance and 100 slaves). Problem does not occur with TCP socket and TCPConnector.

something wrong

Fatal error: Uncaught exception 'InvalidArgumentException' with message 'First parameter must be a valid stream resource' in /Library/WebServer/Documents/www/comm/weixin/vendor/react/stream/src/Stream.php:40 Stack trace: #0 /Library/WebServer/Documents/www/comm/weixin/modules/chart/home.php(14): React\Stream\Stream->__construct('STDOUT', Object(React\EventLoop\StreamSelectLoop)) #1 [internal function]: modules\chart\home->index() #2 /Library/WebServer/Documents/www/comm/weixin/core/router.php(414): call_user_func_array(Array, Array) #3 /Library/WebServer/Documents/www/comm/weixin/core/router.php(391): router->load_route('modules\chart\h...', 'index', Array) #4 /Library/WebServer/Documents/www/comm/weixin/core/router.php(315): router->exec() #5 /Library/WebServer/Documents/www/comm/weixin/public/index.php(50): router::run() #6 {main} thrown

code id here

namespace modules\chart; use React\EventLoop\Factory; use React\Socket\Server; use React\Stream\Stream; class home{
public function index(){
	
	$loop = Factory::create();

	$client = stream_socket_client('tcp://127.0.0.1:1337');
	$conn = new  Stream($client, $loop);
	$conn->pipe(new Stream(STDOUT, $loop));
	$conn->write("Hello World!\n");

	$loop->run();


}
public function background(){
	$loop = Factory::create();

	$socket = new Server($loop);
	$socket->on('connection', function ($conn) {
	    $conn->write("Hello there!\n");
	    $conn->write("Welcome to this amazing server!\n");
	    $conn->write("Here's a tip: don't say anything.\n");

	    $conn->on('data', function ($data) use ($conn) {
	        $conn->close();
	    });
	});
	$socket->listen(1337);

	$loop->run();


}

}

Strange unexpected behaviour

The following code outputs each request twice, any idea why? I think it might be a bug, but IDK if I am honest if I am doing something stupid

<?php

define( 'PORT', 3000 );
define( 'IP', '0.0.0.0' );

require_once __DIR__ . '/vendor/autoload.php';

//Our HTTP Server
$loop = React\EventLoop\Factory::create();
$socket = new React\Socket\Server( $loop );
$http = new React\Http\Server( $socket );
$http->on(
        'request',
        function ( React\Http\Request $request,  React\Http\Response $response $

                echo "request rec'd '' {$request->remoteAddress}\n";
                $response->writeHead( 200, [ 'Content-Type' => 'text/plain' ] );
                $response->end( var_export( $request, true ) );

        }
);
$socket->listen( PORT, IP );
echo "Running on ".IP.":".PORT."...\n";
$loop->run();

Server::listen() is blocking if given a hostname

Migrated from reactphp/reactphp#181, originally reported 2013-04-13

Calling Socket\Server::listen($port, $host) with a hostname instead of an IPv4 address is a blocking operation.

Example:

$server = new Socket\Server($loop);
$server->listen(1234, 'example.com');

Giving a hostname will result in resolving it via DNS (blocking).

Also expose port for each connection

Currently, the Connection::getRemoteAddress() method only returns the IP address of the remote peer.

There's currently no way to access its TCP/IP port.

It's quite trivial to add a getRemotePort() method, but we should think twice about whether we should limit ourselves to TCP/IP here.

Other schemes (such as Unix or perhaps even raw sockets) do not have a concept of "ports" and may not necessarily build on top of IP.

As such, we should consider just returning the full remote peer address from the getRemoteAddress() method.

$loop visibility prevent from extending Server

Hi,
in Server class
loop property is defined as private

Is there a specific reason for this?
Could it be protected?
Class can't be extended because of that...
Reason why one would extend: add context options or flags to stream_socket_server

UDP Support

This is more of a question/discussion around UDP support to socket library.

My initial thinking as is to do the following:

  • Modify React\Socket\Server::__construct() as following
    public function __construct(LoopInterface $loop, $protocol = 'tcp')
    {
        $this->loop = $loop;
        $this->protocol = $protocol;
    }
  • Create TCP/UDP server based on $protocol in React\Socket\Server::listen() as following
        if ($this->protocol == 'tcp')
            $this->master = @stream_socket_server("tcp://$host:$port", $errno, $errstr);
        else
            $this->master = @stream_socket_server("udp://$host:$port", $errno, $errstr, STREAM_SERVER_BIND);
  • And then what? stream_socket_accept doesn't work with UDP so there is no $client (React\Socket\Connection) as such. One implementation can be to emit a udp event like so:
       // inside React\Socket\Server::listen()
       if ($this->protocol == 'tcp')
        {
            $this->loop->addReadStream($this->master, function ($master) {
                $newSocket = stream_socket_accept($master);
                if (false === $newSocket) {
                    $this->emit('error', array(new \RuntimeException('Error accepting new connection')));

                    return;
                }
                $this->handleConnection($newSocket);
            });
        }
        else
        {
            $this->loop->addReadStream($this->master, function($master)
            {
                $data = stream_socket_recvfrom($this->master, 1024, 0, $peer);
                $this->emit('udp', array($master, $data, $peer));
            });
        }
  • And then one can respond back to udp request like so:
    $socket = new React\Socket\Server($loop, 'udp');
    $socket->on('udp', function($socket, $data, $peer)
    {
        echo "$peer -> $data \n";
        stream_socket_sendto($socket, $data, 0, $peer);
    });

What are your thoughts on UDP support?

[Client] Connectors do not honor /etc/hosts

Originally reported 2015-05-31 by @clue: reactphp-legacy/socket-client#35

There's currently no way to connect to "localhost" or any other host names listed in the local /etc/hosts file. We could provide a hard-coded default for some common host names (like "localhost"), but this is bound to break.

In particular, this also affects usage with linked Docker containers where one container references another container by its host name. This means that there's currently no way to connect to other containers by their name.

Opening this ticket as a reminder - this actually depends on reactphp/dns#10

Http streaming client

Is it possible to write a http streaming client using React?

I have an application which connects to a server and the connection remains open and data is passed through that stream

SOCK_SEQPACKET support

To refactor a current project with a SOCK_SEQPACKET unix domain socket I was seeking to use reactphp. This seemed impossible because the stream_socket_* functions does not support this type of socket (but lower level socket_* functions do).

The issue I'm facing is the event loop is using stream_select, which is incompatible with the resources created by socket_create (which i need to use for a SOCK_SEQPACKET socket).

I would like to write a solution for this in reactphp but I need some thoughts on design considerations:

  • Should I need a SocketSelectLoop that runs alternating with the StreamSelectLoop? Is there a better way?
  • Should I be pulling on php developers to enable SOCK_SEQPACKET in stream_socket_* functions?
  • Even if php developers would implement this, would it be better to have a legacy implementation based on the low level socket_* functions?
  • Where will this new reactphp socket type's source code reside? In the reactphp/socket codebase, or a new module?

Thank you for any thoughts on this.

With kind regards,
Joffrey

Why is `$loop` private?

When creating a subclass of the socket server I am forced to override the constructor if I want to access the loop. What is the argument for making $loop private instead of protected?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.