code:
bool Recv(char* rbuf, unsigned int length, unsigned int& actual, int timeout /* ms */)
{
timeval t;
t.tv_sec = timeout / 1000;
t.tv_usec = (timeout - t.tv_sec*1000) * 1000;
fd_set fr;
FD_ZERO(&fr);
FD_SET(_cs, &fr);
unsigned int read = 0;
int n = 0;
while ( read < length )
{
n = select(1, &fr, 0, 0, &t);
if ( n != 1 ) return false; // timeout
//
n = recv(_cs, rbuf + read, length - read, MSG_PEEK);
if (n == SOCKET_ERROR) return false;
for (unsigned int c=read; c<(read+n); c++)
{
if (rbuf[c]=='\r')
{
recv(_cs, rbuf + read, length - read, 0);
actual = read + c + 1;
return true;
}
}
recv(_cs, rbuf + read, length - read, 0);
read += n;
}
return true;
}
code:
DWORD time_left = receive_wait_time;
DWORD len = 0;
while (time_left > 0)
{
len = 0;
ioctlsocket(source.socket, FIONREAD, &len);
if (len > 0)
break;
time_left -= receive_check_interval;
Sleep(receive_check_interval);
}
if (len == 0)
{
*log << "nothing received" << std::endl;
actual_count = 0;
return 0;
}
int recvd = recv(source.socket, rbuf, to_recv, 0);
if (recvd == SOCKET_ERROR)
{
*log << Logger::error << "recv failed with error " << WSAGetLastError() << std::endl;
actual_count = 0;
log->pop_func_name();
return 0;
}