首页 > 解决方案 > 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 并且读取被卡住的情况。如何正确设置读取超时?

标签: c++socketsselect

解决方案


推荐阅读