Swoole Coroutine System: waitEvent

4.x is outdated, please check the latest version 22.x


Latest version: pecl install openswoole-22.1.2

Declaration

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

Parameters

resource

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

events

Which event type should be monitored: SWOOLE_EVENT_READ, SWOOLE_EVENT_WRITE, or both SWOOLE_EVENT_WRITE | SWOOLE_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 swoole_last_error() 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 = Swoole\Coroutine\System::waitEvent($stdin, SWOOLE_EVENT_READ, 5);

    if($status !== false)
    {
      echo fgets($stdin);
    }
    else
    {
      echo "Timeout or an error occurred\n";
      echo swoole_last_error() . "\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, SWOOLE_EVENT_READ | SWOOLE_EVENT_WRITE);
    assert($events === SWOOLE_EVENT_WRITE);

    fwrite($client, "GET / HTTP/1.1\r\nHost: openswoole.com\r\n\r\n");
    $events = Coroutine::waitEvent($client, SWOOLE_EVENT_READ);
    assert($events === SWOOLE_EVENT_READ);

    $response = fread($client, 8192);
    echo $response . "\n";
});
Last updated on August 31, 2022