php - 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()
仅在有任何数据要读取时才调用的行为。我不知道如何实现,所以我在这里问;)
解决方案
默认情况下,读取操作总是阻塞的。您可以使用
socket_set_nonblock($socket)
在调用 read() 以防止套接字在读取操作中阻塞之前,或者您可以使用
socket_select()
在读取数据之前检查数据是否可用。
推荐阅读
- java - 使用 Jfilechooser 编辑仍然打开的文件副本,并在行尾附加 sum
- django - Django 视图 HttpResponseRedirect
- c++ - 我包括了std,但我仍然收到错误,这是为什么呢?
- javascript - javascript--遍历json并在末尾添加累积数
- ocr - 限制 Tesseract 中的空间大小
- game-maker-studio-2 - 低分辨率背景显得模糊
- node.js - POST 请求因身份验证范围不足而失败,而 GET 请求成功
- arrays - 动态列表内的动态列表
- webpack - 使用 webpack mini-css-extract-plugin 插件时出错
- c++ - 显式类型转换的 C++ 转换表示法(C 样式转换)和 static_cast 的多种解释