【问题标题】:Methods to limit bandwidth usage with WinHTTP APIs使用 WinHTTP API 限制带宽使用的方法
【发布时间】:2014-11-11 03:42:09
【问题描述】:

我在类似于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 来限制自己。不幸的是,我从中得到的结果非常出乎意料。我做了一个截图:

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

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

【问题讨论】:

  • 如果您的缓冲区很小(ish),您可以让线程休眠一段适当的时间,以便在下载期间的使用量相当于约 30% 的带宽。
  • @user1793036:嗯,我理解这个理论。你能在代码中说明你的意思吗?

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


【解决方案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() );
}

【讨论】:

  • 谢谢。所以您使用 1,000 位转换为 kbs 而不是 1,024,对吧?
  • 此外,在您的代码中,您可以使用 WinHttpReadDatadwDownloaded 参数中返回的任何内容。但是,如果说,服务器一次“大口”返回 1GB 呢?是否需要将其分解为1000 / 8 字节缓冲区块?
  • 我刚刚注意到的另一件事。当您计算SleepInterval 时,您不会计算下载dwDownloaded 字节以获得kbs 吞吐量所需的时间。所以我并没有真正关注那部分......
  • @c00000fd:1000 指的是毫秒(1000ms = 1sec),而不是一个 kb 中有多少字节。该代码正在计算下载的位数 (dwDownloaded * 8) 并将其乘以 1000 以获得在当前带宽下传输这么多位所需的当前毫秒数,然后将这些毫秒除以所需的速度以获得睡眠间隔需要保持这个速度。此外,一个套接字永远不会返回“1GB in a big gulp”,您最多会得到几 1000 KB 或 1 MB 或 2 个,具体取决于默认的内核缓冲区大小。
  • 嗯。抱歉,如果不知道下载dwDownloaded 字节需要多长时间,我仍然不知道它是如何工作的。我错过了什么吗? WinHttpReadData 是否计量它,例如,仅下载 1 秒或某个预定义的时间量?此外,您的 Sleep(MAXDWORD) 构造有些令人费解。 MAXDWORD ms 大约等于 49 天。您的代码会等待那么久吗?我知道您可能正在尝试展开 64 位变量,但从实际角度来看这没有任何意义......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-28
  • 1970-01-01
相关资源
最近更新 更多