如何使用TcpClient对上传进行评分? [英] How can I rate limit an upload using TcpClient?

查看:95
本文介绍了如何使用TcpClient对上传进行评分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个实用程序,它将上传一堆文件,并希望提供对上传速度进行限制的选项。使用TcpClient类限制上传速率的最佳方法是什么?我的第一个直觉是一次调用有限数量的字节的NetworkStream.Write(),在两次调用之间进入睡眠状态(如果流尚未完成写入,则跳过一次调用),直到缓冲区上载。

I'm writing a utility that will be uploading a bunch of files, and would like to provide the option to rate limit uploads. What is the best approach for rate limiting uploads when using the TcpClient class? My first instinct is to call NetworkStream.Write() with a limited number of bytes at a time, sleeping between calls (and skipping a call if the stream isn't done writing yet) until the buffer is uploaded. Has anyone implemented something like this before?

推荐答案

实施速度限制相对容易,请查看以下代码段:

Implementing speed limit is relatively easy, take a look at the following snippet:

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();

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

This is draft untested code, but I think it is enough to get the main idea.

这篇关于如何使用TcpClient对上传进行评分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆