PHP socket_read 等待数据读取

问题描述

我是 socket 的新手,这是我的一段代码

while (true) {
    $status = $this->client->read();
    echo $status;

    $this->eventQueue->hasEventToSend() ? $this->client->send($this->eventQueue->getEvent()) : null;
}

客户端读取方法就是:

try {
    $status = socket_read($this->socket,$length);
} catch (Throwable $exception) {
    $this->reConnect();
    Log::error($exception->getMessage());

    $status = false;
}

return (string) $status;

$status = $this->client->read() 之后不会执行任何操作,直到 socket_read() 读取新数据。我想停止 socket_read() 的行为就像等待数据读取或仅在有任何数据要读取时才调用 socket_read()。我不知道如何实现,所以我在这里问;)

解决方法

默认情况下,读取操作总是阻塞的。您可以使用

socket_set_nonblock($socket)

在调用read()之前防止socket在读操作中阻塞,或者你可以使用

socket_select()

在读取数据之前检查数据是否可用。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...