3

我正在编写一个将上传一堆文件的实用程序,并希望提供速率限制上传的选项。使用 TcpClient 类时限制上传的最佳方法是什么?我的第一直觉是一次用有限的字节数调用 NetworkStream.Write(),在调用之间休眠(如果流尚未完成写入,则跳过调用),直到上传缓冲区。以前有没有人实施过这样的事情?

4

4 回答 4

7

实现限速相对容易,看下面的代码片段:

const int OneSecond = 1000;

int SpeedLimit = 1024; // Speed limit 1kib/s

int Transmitted = 0;
Stopwatch Watch = new Stopwatch();
Watch.Start();
while(...)
{
    // Your send logic, which return BytesTransmitted
    Transmitted += BytesTransmitted;

    // Check moment speed every five second, you can choose any value
    int Elapsed = (int)Watch.ElapsedMilliseconds;
    if (Elapsed > 5000)
    {
        int ExpectedTransmit = SpeedLimit * Elapsed / OneSecond;
        int TransmitDelta = Transmitted - ExpectedTransmit;
        // Speed limit exceeded, put thread into sleep
        if (TransmitDelta > 0)
            Thread.Wait(TransmitDelta * OneSecond / SpeedLimit);

        Transmitted = 0;
        Watch.Reset();
    }
}
Watch.Stop();

这是未经测试的代码草案,但我认为这足以了解主要思想。

于 2009-07-01T08:27:56.723 回答
1

我知道这是一个旧条目,但我认为这些信息对于通过谷歌或其他网络搜索到达这里的人很有用。

如果我们使用“仲裁者”发布的解决方案,我们会发现线程会发送大量数据,然后它会休眠很长时间,因为通常速度限制超过每秒 32 到 200 kb,而使用标准电脑,线程每秒可以管理超过 10 到 100 MB。

我在我的项目中使用了下一个解决方案。请注意,这只是一段代码,您必须修改它以适应您自己的。它是用 Visual basic 编写的。顺便说一句,对不起我的英语......

    Dim SpeedLimit As Long = User.DownloadKbSpeedLimit * 1024, Elapsed As Long = 0
    'Try to adjust buffersize to the operating system.
    'Seem to be stupid, but the test shows it goes better this way.
    If Environment.Is64BitOperatingSystem Then
        stream.BufferSize = 64 * 1024
    Else
        stream.BufferSize = 32 * 1024
    End If
    'If buffersize is bigger than speedlimite, cut the buffersize to avoid send too much data
    If SpeedLimit > 0 AndAlso e.BufferSize > SpeedLimit Then e.BufferSize = SpeedLimit
    'Create Byte array to send data
    Dim Buffer(e.BufferSize) As Byte
    'Create Watch to control the speed
    Dim Transmitted As Integer = 0, Watch As New Stopwatch()
    Watch.Start()
    'Start sending data
    While True
        'This enables the program to control another events or threads
        System.Threading.Thread.Sleep(10)
        Windows.Forms.Application.DoEvents()
        'Recover data and write into the stream
        If SpeedLimit = 0 OrElse Transmitted < SpeedLimit Then
            Dim Readed As Integer = SomeFileStream.Read(Buffer, 0, Buffer.Length)
            If Readed 0 Then Exit While
            Stream.Write(Buffer, Readed) 
            Transmitted += Readed
        End If
        If Watch.ElapsedMilliseconds > OneSecond Then
            Transmitted = 0
            Watch.Restart()
        End If
    End While
    Watch.Stop()
    Stream.Close() : Stream.Dispose()

希望这可以帮助任何人。再见。

于 2010-09-03T00:07:56.383 回答
1

我对 TcpClient 类做了一些研究,这就是我完成它的方式:

           'Throttle network Mbps...
            bandwidthUsedThisSecond = session.bytesSentThisSecond + session.bytesRecievedThisSecond
            If bandwidthTimer.AddMilliseconds(50) > Now And bandwidthUsedThisSecond >= (Mbps / 20) Then
                While bandwidthTimer.AddMilliseconds(50) > Now
                    Thread.Sleep(1)
                End While
            End If
            If bandwidthTimer.AddMilliseconds(50) <= Now Then
                bandwidthTimer = Now
                session.bytesRecievedThisSecond = 0
                session.bytesSentThisSecond = 0
                bandwidthUsedThisSecond = 0
            End If

如果您决定自己使用它,我相信您知道如何将其转换为 c#,也许这只是我的代码,但它似乎比其他答案更清晰。

这是在主循环中,并且 bandwidthTimer 是一个 Date 对象。

于 2011-12-22T19:37:16.763 回答
1

除了创建这个,您可能还想考虑允许用户(或管理员)配置带宽并处理传输排队的 BITS(后台 Internet 传输服务)。

它确实需要服务器上的特定支持(包括在 IIS 中,但需要启用)。

于 2009-06-30T07:45:41.807 回答