我没怎么写过Socket通讯, 现在用的是CSocket. 我在客户端上发了一个请求之后,如何必须让客户端等待服务器的处理结果,同时也要保证在等不到的时候能够退出。即能够有个超时时间!!!

解决方案 »

  1.   

    各位老大帮忙啊!最好使用CSocket, 发送之后直接调用Receive吗?
      

  2.   

    send请求之后,在你recv的时候,你使用setsockopt来设置接收超时(RECV_TIMEOUT), 这样当你recv服务器回应时你就可以在你指定的时间内等待,超过时间或者收到数据后才会返回.
      

  3.   

    if you want to control timeout using CSocket ,try this way:
    include "stdafx.h"class CSock : public CSocket
    {
    virtual BOOL ConnectHelper(const SOCKADDR* lpSockAddr, int nSockAddrLen);
    virtual void OnClose( int nErrorCode );
    public:
    CSock() { m_Kill = TRUE; }
    BOOL m_Kill;
    };/////  sock.cpp
    #include "stdafx.h"
    #include "Sock.h"/// CSocket modify - timeout module.
    BOOL CSock::ConnectHelper(const SOCKADDR* lpSockAddr, int nSockAddrLen)
    {
    if (m_pbBlocking != NULL)
    {
    WSASetLastError(WSAEINPROGRESS);
    return  FALSE;
    } m_nConnectError = -1; if (!CAsyncSocket::ConnectHelper(lpSockAddr, nSockAddrLen))
    {
    if (GetLastError() == WSAEWOULDBLOCK)
    {
    // Insert....
    CTime curt, st;
    CTimeSpan span(0, 0, 0, m_nTimeOut); st = CTime().GetCurrentTime();
    //.......
    while (PumpMessages(FD_CONNECT))
    {
    if (m_nConnectError != -1)
    {
    WSASetLastError(m_nConnectError);
    return (m_nConnectError == 0);
    }
    // Insert....
    curt = CTime().GetCurrentTime();
    if(curt > (st+span))
    return FALSE;
    //..............
    }
    }
    return FALSE;
    }
    m_Kill = FALSE;
    return TRUE;
    }void CSock::OnClose(int nErrorCode)
    {
    m_Kill = TRUE;
    }