我已經讓我的套接字類工作了一段時間,但我想用select()添加一個超時。看起來很簡單,但我總是從select()返回0。我甚至刪除了select()檢查,因此無論select()如何讀取數據並且讀取數據,但select()仍報告數據不存在。有關如何讓select()停止對我說謊的線索?我也將套接字設置爲非阻塞。謝謝。使用select()檢查socket時數據存在時返回0
代碼:
char buf [ MAXRECV + 1 ];
s = "";
memset (buf, 0, MAXRECV + 1);
struct timeval tv;
int retval;
fd_set Sockets;
FD_ZERO(&Sockets);
FD_SET(m_sock,&Sockets);
// Print sock int for sainity
std::cout << "\nm_sock:" << m_sock << "\n";
tv.tv_sec = 1;
tv.tv_usec = 0;
retval = select(1, &Sockets, NULL, NULL, &tv);
std::cout << "\nretval is :[" << retval << "]\n\n";
// Check
if (FD_ISSET(m_sock,&Sockets))
std::cout << "\nFD_ISSET(m_sock,&Sockets) is true\n\n";
else
std::cout << "\nFD_ISSET(m_sock,&Sockets) is false\n\n";
// If error occurs
if (retval == -1)
{
perror("select()");
std::cout << "\nERROR IN SELECT()\n";
}
// If data present
else if (retval)
{
std::cout << "\nDATA IS READY TO BE READ\n";
std::cout << "recv (m_sock, buf, MAXRECV, 0)... m_sock is " << m_sock << "\n";
int status = recv (m_sock, buf, MAXRECV, 0);
if (status == -1)
{
std::cout << "status == -1 errno == " << errno << " in Socket::recv\n";
return 0;
}
else if (status == 0)
{
return 0;
}
else
{
s = buf;
return status;
}
}
// If data not present
else
{
std::cout << "\nDATA WAS NOT READY, TIMEOUT\n";
return 0;
}
是的,我完全同意,好多了。我現在的設置是處理2個套接字,一個同步和一個異步。但我敢肯定要重寫來實現你的方法。 – Matt