OpenOpenSwoole\Constant::Coroutine System: waitEvent

Latest version: pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5


<?php OpenSwoole\Coroutine\System::waitEvent(mixed $resource, int $events = OpenSwoole\Constant::EVENT_READ, float $timeout = -1): int|false



Can be a PHP resource such as a socket or php_stream, OpenSwoole\Process, OpenSwoole\Coroutine\Client, fd.


Which event type should be monitored: OpenSwoole\Constant::EVENT_READ, OpenSwoole\Constant::EVENT_WRITE, or both OpenSwoole\Constant::EVENT_WRITE | OpenSwoole\Constant::EVENT_READ


A float in seconds defining how long the process should wait before giving up and returning control. Because a float is used, it means that 2.5 is 2.5 seconds. Minimum value is 0.001 and the default -1 means to never time out, wait for the other process to finish.


On success, if the trigger is detected it returns the type of event that was triggered, possibly multiple if both read and write were specified. Returns false when there was an error, use OpenSwoole\Util::getLastErrorCode() for details on what went wrong.


Wait for an I\O event to finish within the current coroutine context. The coroutine will wait until the event signal is triggered. This blocks the current coroutine until the signal is triggered, allowing the coroutine to resume again.


Usage with stdin


    $stdin = fopen("php://stdin", 'r');

    // Timeout of 5 seconds
    $status = OpenSwoole\Coroutine\System::waitEvent($stdin, OpenSwoole\Constant::EVENT_READ, 5);

    if($status !== false)
      echo fgets($stdin);
      echo "Timeout or an error occurred\n";
      echo OpenSwoole\Util::getLastErrorCode() . "\n";

Usage with blocking client

You can use the waitEvent function to convert blocking code into non-blocking code, allowing other coroutines to resume:


    $client = stream_socket_client('tcp://', $errno, $errstr, 30);
    $events = Coroutine::waitEvent($client, OpenSwoole\Constant::EVENT_READ | OpenSwoole\Constant::EVENT_WRITE);
    assert($events === OpenSwoole\Constant::EVENT_WRITE);

    fwrite($client, "GET / HTTP/1.1\r\nHost:\r\n\r\n");
    $events = Coroutine::waitEvent($client, OpenSwoole\Constant::EVENT_READ);
    assert($events === OpenSwoole\Constant::EVENT_READ);

    $response = fread($client, 8192);
    echo $response . "\n";
Last updated on September 20, 2022