使用WinHTTP API限制带宽使用的方法

时间:2014-11-11 03:42:09

标签: c++ windows winapi winhttp bandwidth-throttling

我在类似于this article底部的C ++代码中使用WinHTTP API。它从我的Windows服务运行,用于在后台下载更新。该代码工作正常,但我收到的投诉是,在下载更新时,代码会占用客户端计算机上可用的太多带宽。

有没有办法让这些WinHTTP API,特别是WinHttpQueryDataAvailableWinHttpReadData限制他们使用多少带宽?比如说,高达30%的可用带宽。

PS。为了便于参考,我将复制我在MSDN article中引用的代码:

DWORD dwSize = 0;
DWORD dwDownloaded = 0;
LPSTR pszOutBuffer;
BOOL  bResults = FALSE;
HINTERNET  hSession = NULL, 
           hConnect = NULL,
           hRequest = NULL;

// Use WinHttpOpen to obtain a session handle.
hSession = WinHttpOpen( L"WinHTTP Example/1.0",  
                        WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
                        WINHTTP_NO_PROXY_NAME, 
                        WINHTTP_NO_PROXY_BYPASS, 0);

// Specify an HTTP server.
if (hSession)
    hConnect = WinHttpConnect( hSession, L"www.microsoft.com",
                               INTERNET_DEFAULT_HTTPS_PORT, 0);

// Create an HTTP request handle.
if (hConnect)
    hRequest = WinHttpOpenRequest( hConnect, L"GET", NULL,
                                   NULL, WINHTTP_NO_REFERER, 
                                   WINHTTP_DEFAULT_ACCEPT_TYPES, 
                                   WINHTTP_FLAG_SECURE);

// Send a request.
if (hRequest)
    bResults = WinHttpSendRequest( hRequest,
                                   WINHTTP_NO_ADDITIONAL_HEADERS,
                                   0, WINHTTP_NO_REQUEST_DATA, 0, 
                                   0, 0);


// End the request.
if (bResults)
    bResults = WinHttpReceiveResponse( hRequest, NULL);

// Keep checking for data until there is nothing left.
if (bResults)
{
    do 
    {
        // Check for available data.
        dwSize = 0;
        if (!WinHttpQueryDataAvailable( hRequest, &dwSize)) 
        {
            printf( "Error %u in WinHttpQueryDataAvailable.\n",
                    GetLastError());
            break;
        }

        // No more available data.
        if (!dwSize)
            break;

        // Allocate space for the buffer.
        pszOutBuffer = new char[dwSize+1];
        if (!pszOutBuffer)
        {
            printf("Out of memory\n");
            break;
        }

        // Read the Data.
        ZeroMemory(pszOutBuffer, dwSize+1);

        if (!WinHttpReadData( hRequest, (LPVOID)pszOutBuffer, 
                              dwSize, &dwDownloaded))
        {                                  
            printf( "Error %u in WinHttpReadData.\n", GetLastError());
        }
        else
        {
            printf("%s", pszOutBuffer);
        }

        // Free the memory allocated to the buffer.
        delete [] pszOutBuffer;

        // This condition should never be reached since WinHttpQueryDataAvailable
        // reported that there are bits to read.
        if (!dwDownloaded)
            break;

    } while (dwSize > 0);
}
else
{
    // Report any errors.
    printf( "Error %d has occurred.\n", GetLastError() );
}

// Close any open handles.
if (hRequest) WinHttpCloseHandle(hRequest);
if (hConnect) WinHttpCloseHandle(hConnect);
if (hSession) WinHttpCloseHandle(hSession);

编辑:在跟进@RemyLebeau建议时,我创建了一个测试C ++项目(您可以download it from here),该项目尝试计算上述方法使用的当前下载速率并使用“睡眠”API来限制自己。不幸的是,我从中得到的结果是非常意外的。我做了一个截图:

enter image description here

查看我的阅读与任务管理器给我的区别。 (请注意,在我运行这些测试时没有使用带宽。)

我一定错过了什么。问题是什么?

1 个答案:

答案 0 :(得分:1)

通过“30%的可用带宽”来节制并不总是很容易,因为您必须知道“可用带宽”实际上是什么,并且可能并不总是很容易确定。我想你可以为每个循环迭代计时,根据每次读取的时间长度来计算可能的带宽。但是,随着带宽被用于其他事情,这种情况可能会有所波动,并且当您限制带宽使用时,可用带宽的计算将受到影响。

实现的更常见(通常更容易)是通过所需的“每(毫秒)字节数”来代替。你无法限制WinHttpReadData()本身,但你可以限制你调用它的频率。只需跟踪您正在读取的字节数并休眠循环迭代,这样您就不会读取超过所需节流速度的太多字节 - 睡眠时间越长越慢,睡眠越短以加速,例如:

// Keep checking for data until there is nothing left.
if (bResults)
{
    char *pszOutBuffer = NULL;
    DWORD dwOutBufferSize = 0;

    do 
    {
        // Check for available data.

        // RL: personally, I would not bother with WinHttpQueryDataAvailable()
        // at all.  Just allocate a fixed-size buffer and let WinHttpReadData()
        // tell you when there is no more data to read...

        dwSize = 0;
        if (!WinHttpQueryDataAvailable( hRequest, &dwSize)) 
        {
            printf( "Error %u in WinHttpQueryDataAvailable.\n", GetLastError());
            break;
        }

        // No more available data.
        if (!dwSize)
            break;

        // (re)Allocate space for the buffer.
        if (dwSize > dwOutBufferSize)
        {
            delete [] pszOutBuffer;
            pszOutBuffer = NULL;
            dwOutBufferSize = 0;

            pszOutBuffer = new char[dwSize];
            if (!pszOutBuffer)
            {
                printf("Out of memory\n");
                break;
            }

            dwOutBufferSize = dwSize;
        }

        // Read the Data.
        DWORD dwStart = GetTickCount();
        if (!WinHttpReadData(hRequest, pszOutBuffer, dwSize, &dwDownloaded))
        {                                  
            printf("Error %u in WinHttpReadData.\n", GetLastError());
            break;
        }
        DWORD dwEnd = GetTickCount();
        DWORD dwDownloadTime = (dwEnd >= dwStart) ? (dwEnd - dwStart) : ((MAXDWORD-dwStart)+dwEnd);
        if (dwDownloadTime == 0) dwDownloadTime = 1;

        printf("%.*s", dwDownloaded, pszOutBuffer);

        // throttle by bits/sec
        //
        // todo: use a waitable object to sleep on, or use smaller
        // sleeps more often, if you need to abort a transfer in
        // progress during long sleeps...

        __int64 BitsPerSec = (__int64(dwDownloaded) * 8) * 1000) / dwDownloadTime;
        if (BitsPerSec > DesiredBitsPerSec)
            Sleep( ((BitsPerSec - DesiredBitsPerSec) * 1000) / DesiredBitsPerSec );
    }
    while (true);

    // Free the memory allocated to the buffer.
    delete [] pszOutBuffer;
}
else
{
    // Report any errors.
    printf( "Error %d has occurred.\n", GetLastError() );
}