Search code examples
phpwebsocketreactphp

ReactPHP Socket Client Connection Timeout


We're using ReactPHP to establish a websocket connection and listen for some data. It works great as long as the websocket server is up and running.

If it can't make the websocket connection, I need it to retry after a few seconds, but can't get that far ...

What I can't figure out is how to get ReactPHP's Socket Client to fail when it can't connect (or the websocket server goes offline). I've tried things like the TimeoutConnector and what's below, but no matter what happens, it just, well, does nothing, like it's connected:

$connector = new \React\Socket\Connector();
$connector->connect('localhost:1234')->then(
        function (ConnectionInterface $connection) {
            $connection->on('data', function ($data) use ($connection) {
                    ... do all the things ...
            });
            $connection->on('end', function () use ($connection) {
                echo 'end';
            });
            $connection->on('close', function () use ($connection) {
                echo 'close';
            });
            $connection->on('error', function () use ($connection) {
                echo 'error'
            });
        },
        function (Exception $e) {
            echo $e->getMessage();
        }
);

Note that I can get the 'end' and 'close' events to fire after a successful connection, I just can't get any events to fire if when starting the ReactPHP app the websocket server is offline and it can't connect, just kinds of hangs there like its connected, ignoring any timeouts.

Thanks for any help or advice :)


Solution

  • I already wrote an answer in https://github.com/orgs/reactphp/discussions/502, but I will also post the same answer here for better visibility.

    I'm not 100% sure, but I think the problem lies in your namespacing. If an error occurs inside your promise, you would expect to echo the message with the help of your rejection handler, but I think it can't match the specific Exception thrown. This all is happening inside a promise and promises are currently swallowing exceptions and errors in the current version if not handled correctly. We're aware of this behavior and are working towards better error handling for this with ReactPHP v3, you can read more about this in our ReactPHP v3 wish list discussion.

    I can't see your use statements in this example, so I can't really tell if this is the exact problem, but I think you want to use \Exception instead of Exception here. Let me know if this solves you're problem.