wiki:TBR/UserManual/Receive_Socket_Timeout

Version 1 (modified by JohnHeard, on Oct 18, 2006 at 10:45:27 AM) (diff)

/* Receive Socket Timeout */

Receive Socket Timeout

Receive Socket Timeout

Applications sometimes need its threads to timeout on a socket that blocks when reading. The following is an example function from IanCaddy? (ianc AT microsol DOT iinet DOT net DOT au):

int SetSocketTimeout?(int connectSocket, int milliseconds) {

struct timeval tv;

tv.tv_sec = milliseconds / 1000 ; tv.tv_usec = ( milliseconds % 1000) * 1000 ;

return setsockopt (connectSocket, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof tv);

}

Note that by applying the SO_RCVTIMEO option the socket mode is changed to non-blocking. You should test 'errno' for EWOULDBLOCK (or EAGAIN) if a socket function fails.

Then when you are waiting to receive a packet, use the following function:

iRc = recv(connectSocket, pTmpRxBuffer, MessageDataLen?, 0 );

if (iRc == 0) {

/* Socket has been disconnected */ printf("\nSocket EOF\n");

close(connectSocket); connectSocket = 0; return iRc;

}

if(iRc < 0) {

printf("\nSocket recv returned %d, errno %d\n",iRc,errno);

if (errno != EWOULDBLOCK) {

close(connectSocket); /* Close socket if we get an error */ connectSocket = 0;

}

}

If <tt>iRc</tt> is positive, it gives you the number of chars received.