Click to See Complete Forum and Search --> : Time out in MFC Sockets


Samir Sanghani
May 9th, 1999, 03:10 AM
How can I specify a timeout value with my MFC Sockets in receive mode. It seems that my socket is just stalled if the other end disconnects while this end is in receive mode. Any body can guide me doing this either with MFC sockets or even with WinSock.

Thanks
Samir

William Walseth
May 10th, 1999, 11:55 AM
Here's some sample code to set the time-out

// First create a socket.
void CSocketClass::Create(int nType /* = SOCK_STREAM */)
{
ASSERT(m_hSocket == NULL);
if((m_hSocket = socket(AF_INET, nType, 0)) == INVALID_SOCKET)
{
throw new YourException
}
}



// Set's time-out for the socket.
void CSocketClass::SetTimeout(int nTimeout ) // in seconds.
{
// Set the socket timeout for reply messages
m_nTimeout = nTimeout;
nTimeout *= 1000; // convert to milliseconds.
if( setsockopt(m_hSocket, SOL_SOCKET, SO_RCVTIMEO,
(char *) &nTimeout, sizeof( int ) ) == SOCKET_ERROR) {
throw new YourException()
}
return;
}

May 14th, 1999, 09:23 AM
Hi.
It doesn't work.
If you try SDK sample, ping test. It becomes blocked if there's nothing to receive.

Dima.

Samir Sanghani
May 16th, 1999, 04:40 AM
The code won't work because winsock documentation itself says that it is not supporting any timeout option with receive or send.
I even tried attaching a window with my socket using class and using a window timer event. but everything is on hold when i am in blocking receive method.
in case you have that code working in some example and send the example that would be useful.
Thanks for replying.
Samir

Dima Semenov
May 23rd, 1999, 04:20 PM
There's better way to time out sockets.
Use function select, where you can set timeout and what you expect from socket, here's some code:

int CSSocket::WaitForData(int timeout) // pure timeout for socket
{
FDSET fd;
fd.count = 1;
fd.sockarr[0] = m_Socket;

TIMEVAL tv;
tv.tv_sec = timeout/1000;
tv.tv_usec = timeout*1000 - tv.tv_sec * 1000000;

return select(0, (FD_SET*)&fd, NULL, (FD_SET*)&fd, &tv);
}

It returns either timeout, socket_error or somedata wait for being receiving
Hope it'l help