如何检索特定的ReactPHP套接字错误?

时间:2017-01-12 16:32:26

标签: php sockets reactphp

以下内容有一个错误事件。如何确定具体错误?

<?php
$loop = Factory::create();
$socket = new React\Socket\Server($loop);
$socket->on('connection', function (\React\Socket\ConnectionInterface $stream){

    $stream->on('data', function($rsp) {
        echo('on data');
    });

    $stream->on('close', function($conn) {
        echo('on close');
    });

    $stream->on('error', function($conn) use ($stream) {
        echo('on error');
        // How do I determine the specific error?
        $stream->close();
    });

    echo("on connect");
});

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

1 个答案:

答案 0 :(得分:3)

查看ConnectionInterface React\Socket\Connection的实现,它扩展了React\Stream\Stream,它使用emit()(将触发向on注册的回调): https://github.com/reactphp/stream/blob/c3647ea3d338ebc7332b1a29959f305e62cf2136/src/Stream.php#L61

$that = $this;
$this->buffer->on('error', function ($error) use ($that) {
    $that->emit('error', array($error, $that));
    $that->close();
});

因此,该函数的第一个参数是错误,第二个参数是$stream

$stream->on('error', function($error, $stream) {
    echo "an exception happened: $error";
    // $error will be an instance of Throwable then
    $stream->close();
});