Search code examples
phpsocketsreactphp

Detecting if React PHP client cannot connect to server


How can it be detected that a React PHP client cannot connect with a server? I was hoping for the fictional else() method that I showed at the bottom. Do I just need to wait a reasonable amount of time, and if no on data event occurs, it isn't connected.

<?php

require 'vendor/autoload.php';

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

$dnsResolverFactory = new React\Dns\Resolver\Factory();
$dns = $dnsResolverFactory->createCached('8.8.8.8', $loop);
$connector = new React\SocketClient\Connector($loop, $dns);

$connector->create('127.0.0.1', 1337)->then(function (React\Stream\Stream $stream) {
    $buffer = '';
    $stream->on('data', function ($data, $stream) use (&$buffer) {
    });
})
/*
->else(function () {
    //no connection?
});
*/

$loop->run();

Solution

  • Have a look at ReactPHP's PromiseInterface. Either use a second callback for then or use otherwise, which is exactly your artificial else.

    $connector->create('127.0.0.1', 1337)->then(function (React\Stream\Stream $stream) {
        $buffer = '';
        $stream->on('data', function ($data, $stream) use (&$buffer) {
            // ...
        });
    }, function (Throwable $error) {
        // handle error here
    });