I already had my socket class, but I wanted to add a timeout using select (). It seems pretty straight forward, but I always have 0 returned by the select () function. I even deleted check () so that it reads the data regardless of select () and the data is read, but select () still reports that there is no data. Any clue on how to get select () to stop lying to me? I also found that the socket is not blocking. Thanks.
the code:
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; }
source share