Skip to content
Advertisement

Ratchet client event loop wait for finish

I have the following test php code:

use ReactEventLoopLoop;
$loop = Loop::get();
$reason = "unknown";

RatchetClientconnect('wss://demo.piesocket.com/v3/channel_1?api_key=VCXCEuvhGcBDP7XhiJJUDvR1e1D3eiVjgZ9VRiaV&notify_self', [], [], $loop)->then(function($conn) use ($loop, &$reason){
    $conn->on('message', function($msg) use ($loop, $conn, &$reason){
        echo $msg."n";
        if ($msg == "quit") {
            $conn->close();
            $loop->stop();
            $reason = "quit";
        }
    });
}, function ($e) {
    echo "Could not connect: {$e->getMessage()}n";
});

echo "the echo $reasonn";

The code mostly works, it connects to the websocket and prints messages on the command line that are sent through the websocket. Also when I send quit it stops the connection and the script ends.

However the last echo in the script, the “the echo $reason” echo, is printed first thing the script starts. I would like to somehow wait for the websocket to finish and then run the echo statement. How do I do this?

In the end the websocket code is going to be a small subroutine of a bigger script. I want the bigger script to wait for the subroutine to finish.

Advertisement

Answer

Add

$loop->run();

before the echo, the run() will block the thread until it has finished. So the echo will be printed at the end of the script and the $reason will be filled in as expected.

The Loop::get() function has this comment:

Automatically run loop at end of program, unless already started or stopped explicitly.

So if you did not start it manually, it will start it at the end of the script. In my opinion a weird feature, but running it manually bypasses it.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement