问题描述
我是 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()
在读取数据之前检查数据是否可用。