Detecting if React PHP client cannot connect to server

时间:2017-04-24 17:35:19

标签: php sockets reactphp

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

2 个答案:

答案 0 :(得分:1)

看看ReactPHP的PromiseInterface。要么使用then的第二个回调,要么使用otherwise,这正是你的人为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
});

答案 1 :(得分:0)

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

$gotConnected=false;

$connector->create('127.0.0.1', 1337)->then(function (React\Stream\Stream $stream) use(&$gotConnected) {
    $gotConnected=true;
    $buffer = '';
    $stream->on('data', function ($data, $stream) use (&$buffer) {
    });
});

$loop->run();

echo($gotConnected?'Got connected':'Did not get connected');