CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    May 1999
    Posts
    5

    Time out in MFC Sockets

    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



  2. #2
    Join Date
    Apr 1999
    Location
    Arlington, VA
    Posts
    21

    Here's some WinSock code to set time-out


    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;
    }




  3. #3
    Guest

    Re: Here's some WinSock code to set time-out

    Hi.
    It doesn't work.
    If you try SDK sample, ping test. It becomes blocked if there's nothing to receive.

    Dima.


  4. #4
    Join Date
    May 1999
    Posts
    5

    Re: Here's some WinSock code to set time-out

    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


  5. #5
    Join Date
    May 1999
    Posts
    8

    Re: Time out in MFC Sockets

    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


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured