Tuesday, July 20, 2010

winsock 2: recv with select

needed to use recv in synchronous mode. but it is a blocking call.
so google a bit and found select.

code segment:

fd_set sockets;
TIMEVAL waitTime;

void Receive()
{
// gotta call select() to check if there is incoming packet
sockets.fd_count = 1;
sockets.fd_array[0] = ClientSocket;

// time to expire for select call. since it is blocking too.
waitTime.tv_sec = 0; // seconds
waitTime.tv_usec = 100; // micro seconds

// check if any of the listening sockets has incoming data
// returns number of sockets in fd_set that has incoming data
int result = select(NULL, &sockets, NULL, NULL, &waitTime);

int iResult = result;
if(result > 0)
{
// blocking call
iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
if(iResult > 0)
{
printf("Bytes received: %d\n", iResult);
printf("Recv: %s\n", recvbuf);
}
else if(iResult == 0)
{
//printf("Nothing received\n");
}
else
{
printf("recv failed: %d\n", WSAGetLastError());
}
}
return iResult;
}

No comments: