c++ - c++ 读取套接字超时
问题描述
我在读取套接字时遇到问题。我使用 Select 来检查数据是否存在,并使用 read 来读取套接字数据。
FD_ZERO(&rfd);
FD_SET(socket, &rfd);
this->timeout.tv_sec = 0;//need both setted
this->timeout.tv_usec = MS_500 * 1000;
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof timeout);
cout<<"try to read"<<endl;
if (select(socket + 1, &rfd, NULL, NULL, &timeout) > 0) {
if ((readedByte = read(socket, &buffer, sizeof(buffer))) < 0) {
cout<<"ERROR"<<endl;
PLOG_ERROR_(MemoryHandler::INFO) << "Error reading serial";
} else {
buffer[readedByte - 1] = '\0';
string tempString = buffer;
cout<<tempString<<endl;
}
有时会发生套接字返回值 >0 并且读取被卡住的情况。如何正确设置读取超时?
解决方案
推荐阅读
- erp - 我们如何在 Infor syteline 中添加自定义字段
- javascript - Next.js 自定义 App getInitialProps TypeError
- substrate - 如何将呼叫数据编码到合同中
- google-colaboratory - 如何将文件上传到 Google Colab 笔记本中的当前工作目录?
- angular - 获取嵌入在 Angular 应用程序中的 Power BI 的嵌入式令牌
- amazon-s3 - 带有 Steaming File Sink 到 S3 的 Flink 1.9 不起作用
- php - 日历日期返回-1天,有什么问题,替代解决方案?
- amazon-emr - 通过 Step Functions 在 EMR 集群配置中设置子网 ID 和 EC2 密钥名称
- python - 增加pandas python中的地块大小
- macos - 如何修复 OSX Catalina 上的终端“源”命令