OpenOpenSwoole\Constant::Coroutine System: waitEvent

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

Declaration

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

Parameters

resource

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

events

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

timeout

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.

Return

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.

Description

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.


Example

Usage with stdin

<?php

co::run(function()
{
    $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);
    }
    else
    {
      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:

<?php

co::run(function()
{
    $client = stream_socket_client('tcp://openswoole.com:80', $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: openswoole.com\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