InternetConnect超时的问题

wininet 里面的InternetConnect是不能设置超时参数的,一旦遇到特殊情况,就会一直阻塞在这里,有时候阻塞几个小时,所以这里一定要自己处理一下。



int Request::ThreadInternetConnect(PVOID param){

    InternetConnectParam *p_connect_param = (InternetConnectParam*)param;
    p_connect_param->hSession = NULL;
    // 打开http session     
    p_connect_param->hSession = InternetConnect(p_connect_param->hInternet, p_connect_param->host.c_str(),
        (INTERNET_PORT)p_connect_param->port, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);

    return 1;
}

BOOL Request::Http(){
     // ......此处省略前面的代码.......
    hInternet = InternetOpen(user_agent.c_str(),
        INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
    if (NULL == hInternet)
    {
        wsprintfA(szTempText, "InternetOpen error. ErrCode=[%u]", GetLastError());
        response.error_msg = szTempText;
        InternetCloseHandle(hInternet);
        return FALSE;
    }

    // 打开http session    

    /*
    HINTERNET hSession = InternetConnect(hInternet, host.c_str(),
        (INTERNET_PORT)nPort, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
    */
    
    //InternetConnect连接某些情况会超时,使用线程来InternetConnect,超时则直接结束线程
    InternetConnectParam param;
    param.hInternet = hInternet;
    param.host = host;
    param.port = nPort;

    HANDLE hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadInternetConnect, (LPVOID)¶m, 0, NULL);
    //超时10秒,如果等待结果是超时
    if (WaitForSingleObject(hThread, 10 * 1000) == WAIT_TIMEOUT){
        response.error_msg += "InternetConnect error. ErrCode=[connect timeout]";

        TerminateThread(hThread, 0);
        CloseHandle(hThread);
        param.hSession = NULL;
    }

    HINTERNET hSession = param.hSession;
    
    if (!hSession){
        wsprintfA(szTempText, "InternetConnect error. ErrCode=[%u]", GetLastError());
        response.error_msg += szTempText;
    
        InternetCloseHandle(hSession);
        InternetCloseHandle(hInternet);
        return FALSE;
    }

 // ......此处省略后面的代码.......

}

你可能感兴趣的:(InternetConnect超时的问题)