Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I rate limit an upload using TcpClient?

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?

like image 618
Luke Avatar asked Nov 21 '25 09:11

Luke


1 Answers

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.

like image 147
arbiter Avatar answered Nov 23 '25 23:11

arbiter