phpday 2027 - Call for Papers

The Io\Poll\Context class

(PHP 8 >= 8.6.0)

Введение

A polling context watches a set of handles and reports which of them are ready for reading or writing. It is the entry point of the polling API: handles are registered with Io\Poll\Context::add(), and Io\Poll\Context::wait() blocks until one of them is ready.

The context relies on the polling mechanism of the operating system, represented by the Io\Poll\Backend enum. Unlike stream_select(), the set of watched streams is kept between calls instead of being passed again on each of them.

Objects of this class cannot be cloned or serialized.

Обзор класса

namespace Io\Poll;
final class Context {
/* Методы */
public function __construct(Io\Poll\Backend $backend = Io\Poll\Backend::Auto)
public function add(Io\Poll\Handle $handle, array $events, mixed $data = null): Io\Poll\Watcher
public function getBackend(): Io\Poll\Backend
public function wait(?Time\Duration $timeout = null, ?int $maxEvents = null): array
}

Примеры

Пример #1 Waiting for a stream to become readable

<?php
use Io\Poll\Context;
use Io\Poll\Event;
use Time\Duration;

[$reader, $writer] = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);

$context = new Context();
$context->add(new StreamPollHandle($reader), [Event::Read], 'reader');

// Nothing can be read yet, so the wait times out.
var_dump(count($context->wait(Duration::fromMilliseconds(10))));

fwrite($writer, 'ping');

foreach ($context->wait(Duration::fromSeconds(1)) as $watcher) {
    $stream = $watcher->getHandle()->getStream();
    echo $watcher->getData(), ': ', fread($stream, 1024), PHP_EOL;
}

Результат выполнения приведённого примера:

int(0)
reader: ping

Содержание

+Добавить

Примечания пользователей

Пользователи ещё не добавляли примечания для страницы
To Top