Coder Social home page Coder Social logo

socket-client's Introduction

SocketClient Component

Build Status Code Climate

Async Connector to open TCP/IP and SSL/TLS based connections.

Introduction

Think of this library as an async version of fsockopen() or stream_socket_client().

Before you can actually transmit and receive data to/from a remote server, you have to establish a connection to the remote end. Establishing this connection through the internet/network takes some time as it requires several steps in order to complete:

  1. Resolve remote target hostname via DNS (+cache)
  2. Complete TCP handshake (2 roundtrips) with remote target IP:port
  3. Optionally enable SSL/TLS on the new resulting connection

Usage

In order to use this project, you'll need the following react boilerplate code to initialize the main loop.

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

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:

create()

The create(string $host, int $port): PromiseInterface<Stream, Exception> method can be used to establish a streaming connection. It returns a Promise which either fulfills with a Stream or rejects with an Exception:

$connector->create('google.com', 443)->then(
    function (Stream $stream) {
        // connection successfully established
    },
    function (Exception $error) {
        // failed to connect due to $error
    }
);

The returned Promise SHOULD be implemented in such a way that it can be cancelled when it is still pending. Cancelling a pending promise SHOULD reject its value with an Exception. It SHOULD clean up any underlying resources and references as applicable:

$promise = $connector->create($host, $port);

$promise->cancel();

Async TCP/IP connections

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->create('127.0.0.1', 80)->then(function (React\Stream\Stream $stream) {
    $stream->write('...');
    $stream->end();
});

$loop->run();

See also the first example.

Pending connection attempts can be cancelled by cancelling its pending promise like so:

$promise = $tcpConnector->create($host, $port);

$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.

DNS resolution

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', $loop);

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

$dnsConnector->create('www.google.com', 80)->then(function (React\Stream\Stream $stream) {
    $stream->write('...');
    $stream->end();
});

$loop->run();

See also the first example.

Pending connection attempts can be cancelled by cancelling its pending promise like so:

$promise = $dnsConnector->create($host, $port);

$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->create('www.google.com', 80)->then($callback);

Async SSL/TLS connections

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->create('www.google.com', 443)->then(function (React\Stream\Stream $stream) {
    $stream->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->create($host, $port);

$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 a TcpConnector 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.

Connection timeouts

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->create('google.com', 80)->then(function (React\Stream\Stream $stream) {
    // 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->create($host, $port);

$promise->cancel();

Calling cancel() on a pending promise will cancel the underlying connection attempt, abort the timer and reject the resulting promise.

Unix domain sockets

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->create('/tmp/demo.sock')->then(function (React\Stream\Stream $stream) {
    $stream->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.

Install

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.5.3

More details about version upgrades can be found in the CHANGELOG.

Tests

To run the test suite, you need PHPUnit. Go to the project root and run:

$ phpunit

The test suite also contains some optional integration tests which operate on a TCP/IP socket server and an optional TLS/SSL terminating proxy in front of it. The underlying TCP/IP socket server will be started automatically, whereas the TLS/SSL terminating proxy has to be started and enabled like this:

$ stunnel -f -p stunnel.pem -d 6001 -r 6000 &
$ TEST_SECURE=6001 TEST_PLAIN=6000 phpunit

See also the Travis configuration for details on how to set up the TLS/SSL terminating proxy and the required certificate file (stunnel.pem) if you're unsure.

socket-client's People

Contributors

alexmace avatar cboden avatar clue avatar daverandom avatar e3betht avatar elliot avatar igorw avatar jsor avatar robinvdvleuten avatar wyrihaximus avatar

Watchers

 avatar  avatar

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.