首页 > 解决方案 > PHP socket_read 等待数据读取

问题描述

我是套接字的新手,这是我的一段代码:

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()仅在有任何数据要读取时才调用的行为。我不知道如何实现,所以我在这里问;)

标签: phplaravelwebsocketphpwebsocket

解决方案


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

socket_set_nonblock($socket)

在调用 read() 以防止套接字在读取操作中阻塞之前,或者您可以使用

socket_select()

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


推荐阅读