PHP Conference Japan 2024

ZMQPoll::poll

(PECL zmq >= 0.5.0)

ZMQPoll::poll輪詢項目

說明

public ZMQPoll::poll(陣列 &$readable, 陣列 &$writable, 整數 $timeout = -1): 整數

輪詢目前輪詢集合中的項目。可讀和可寫的項目將分別返回到 readablewritable 參數中。可以使用 ZMQPoll::getLastErrors() 來檢查是否有錯誤發生。

參數

readable

返回可讀取 ZMQSockets/PHP 串流的陣列。該陣列將在操作開始時被清空。

writable

返回可寫入 ZMQSockets/PHP 串流的陣列。該陣列將在操作開始時被清空。

timeout

操作逾時時間。-1 表示輪詢將一直等待,直到至少有一個項目有活動。請注意,從版本 1.0.0 開始,輪詢逾時時間以毫秒為單位,而不是微秒。

返回值

返回一個整數,表示具有活動的項目數量。

錯誤/例外

發生錯誤時拋出 ZMQPollException 例外。

範例

範例 #1 ZMQPoll() 範例

建立一個簡單的輪詢伺服器

<?php

/* Create socket, request-reply pattern (reply socket) */
$context = new ZMQContext();
$server = $context->getSocket(ZMQ::SOCKET_REP);

/* Bind to port 5555 on 127.0.0.1 */
$server->bind("tcp://127.0.0.1:5555");

/* Create new pollset for incoming/outgoing message */
$poll = new ZMQPoll();

/* Add the object and listen for poll in/out */
$id = $poll->add($server, ZMQ::POLL_IN | ZMQ::POLL_OUT);
echo
"Added object with id " . $id . "\n";

/* Initialise readable and writable arrays */
$readable = array();
$writable = array();

while (
true) {
/* Amount of events retrieved */
$events = 0;

try {
/* Poll until there is something to do */
$events = $poll->poll($readable, $writable, -1);
$errors = $poll->getLastErrors();

if (
count($errors) > 0) {
foreach (
$errors as $error) {
echo
"Error polling object " . $error . "\n";
}
}
} catch (
ZMQPollException $e) {
echo
"poll failed: " . $e->getMessage() . "\n";
}

if (
$events > 0) {
/* Loop through readable objects and recv messages */
foreach ($readable as $r) {
try {
echo
"Received message: " . $r->recv() . "\n";
} catch (
ZMQException $e) {
echo
"recv failed: " . $e->getMessage() . "\n";
}
}

/* Loop through writable and send back messages */
foreach ($writable as $w) {
try {
$w->send("Got it!");
} catch (
ZMQException $e) {
echo
"send failed: " . $e->getMessage() . "\n";
}
}
}
}
?>

新增註釋

使用者貢獻的註釋

此頁面沒有使用者貢獻的註釋。
To Top