Click here to Skip to main content
Licence CPOL
First Posted 2 Apr 2007
Views 81,025
Downloads 1,521
Bookmarked 92 times

Bandwidth throttling

By | 2 Apr 2007 | Article
Save bandwidth and get QoS with bandwidth throttling.

Screenshot - screen.jpg

Introduction

Hosting a website can be fun. But, when you offer big downloads or streaming media, you do not want a visitor to eat up the full bandwidth. Or, maybe, you want to offer a premium account from where users can download without limitation, and a free account where users cannot download faster than 50 kb/s. Here is where throttling comes in.

Bandwidth throttling helps provide quality of service (QoS) by limiting network congestion and server crashes. For example, you make sure a connection does not get more than an X number of bytes per second.

The purpose of this article is to show how to use bandwidth throttling, with a small helper class.

Using the code

Within the source code, you will find a class named ThrottledStream. This class is derived from the abstract Stream that can be found in the System.IO namespace. In the constructor, it accepts a base stream to throttle. Here is a small line of code that shows how to instantiate a ThrottledStream:

Stream throttledStream = new ThrottledStream(Response.OutputStream, 1024);

Now, everything you do with the throttledStream will be limited to 1024 bytes per second, and will be send to or read from the OutputStream that is a member of the Response property that exists within an ASP.NET page.

Because the ThrottledStream is derived from the abstract Stream class, it is easy to add throttling to an existing application or website. For example, when you have a process that sends file content over a Stream and you want to enable bandwidth throttling, you only have to change the initialization of the destination stream.

The old code can look like this:

Stream sourceStream;
Stream destinationStream;

try
{
    sourceStream = new FileStream(@"c:\myfile.bin", 
                       FileMode.Open, FileAccess.Read, FileShare.Read);
    destinationStream = new NetworkStream(mySocket, false);

    byte[] buffer = new byte[1024];
    int readCount = sourceStream.Read(buffer, 0, BufferSize);

    while (readCount > 0)
    {
        destinationStream.Write(buffer, 0, readCount);
        readCount = sourceStream.Read(buffer, 0, BufferSize);
    }
}
finally
{
    if (destinationStream != null)
    {
        destinationStream.Close();
    }
 
    if (sourceStream != null)
    {
        sourceStream.Close();
    }
}

Now, we can easily add throttling support to this process. We only need to change the initialization:

...

Stream originalDestinationStream = new NetworkStream(mySocket, false);
destinationStream = new ThrottledStream(originalDestinationStream, 51200);

...

By adding only one line of code, this full process is throttled to 50 kb/s (51200 b/s). Now, we go even a step further and add throttling that is based on a membership:

...

long bps;

switch( user.Membership )
{
    case MembershipLevel.Bronze:
        bps = 51200;
        break;

    case MembershipLevel.Silver:
        bps = 102400;
        break;

    case MembershipLevel.Gold:
        bps = 153600;
        break;

    case MembershipLevel.Platina:
        bps = ThrottledStream.Infinite;
        break;
}

Stream originalDestinationStream = new NetworkStream(mySocket, false);
destinationStream = new ThrottledStream(originalDestinationStream, bps);

...

Here, we have a situation where a Bronze membership will give you 50 kb/s, Silver 100 kb/s, Gold 150 kb/s, and Platina infinitive - no throttling.

Points of interest

Bandwidth throttling can improve the QoS of your server, and allows you to control the bandwidth for a specified connection. The helper class named ThrottledStream is very easy to use, and can be used in existing scenarios.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

P.J. van de Sande

Architect
Sogyo
Netherlands Netherlands

Member

Pieter Joost is a sr. IT consultant at Sogyo. He is recently awarded as Microsoft Visual C# MVP. He's active in the software development community as a speaker and boardmember of devnology.nl and dotned.nl

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Questionupload throttled Pinmembernandobv15:10 10 Mar '12  
Generalhow to use ThrottledStream class Pinmemberas206em5:28 19 May '11  
QuestionHow throttle each connection TCP/UDP? Pinmemberegcf11:15 21 Nov '10  
GeneralProblems PinmemberMember 3267472:15 21 Sep '10  
GeneralBandwidth throttling Pinmemberbidel akbari11:07 10 Mar '10  
QuestionWhat with asp.net worker threadpool ? Pinmemberneoandrew14:10 7 Mar '10  
GeneralThanks ! PinmemberAhmed Charfeddine1:17 1 Jun '09  
GeneralIt works! Pinmemberdimitris.dpant14:41 8 May '09  
GeneralRe: It works! Pinmemberdimitris.dpant23:09 15 May '09  
GeneralRe: It works! PinmemberGoran___2:54 20 Aug '09  
QuestionCan I adjust the bit rate on the fly? Pinmemberebonnett6:22 29 Apr '09  
AnswerRe: Can I adjust the bit rate on the fly? Pinmemberst0icsmitty10:25 15 Dec '09  
GeneralRe: Can I adjust the bit rate on the fly? Yes... [modified] Pinmemberthomastmc4:04 5 Feb '10  
GeneralIdle for a while after creating ThrottledStream constructor PinmemberSchoonMan8:07 14 Oct '08  
GeneralNice and idea to an improvement. Pinmemberleandrobecker10:31 25 Jul '08  
GeneralError with StreamReader.ReadLine PinmemberMember 35721415:10 26 Jun '08  
GeneralA few changes to improve accuracy especially on a Read() Pinmemberdeepsquatter6:10 22 May '08  
I found accuracy was not that good when used to buffer reading. I changed the Read() method to:
 

public override int Read(byte[] buffer, int offset, int count)
{
int read = _baseStream.Read(buffer, offset, count);
Throttle(read);
return read;
}

 
Remember reading from a stream (expecially a network stream) can return less that your buffer size. I also found that removing the Reset() produced much better results as a larger sample improves accuracy. Not much chance of any overflows either as you using long everywhere.
GeneralExcellent Pinmemberroyal_roi10:07 25 Mar '08  
Questionwhen will you reset time and bytecount? Pinmembertim40818:21 30 Jan '08  
QuestionIs this really a throttling technique? PinmemberKelmen Wong23:20 27 Sep '07  
AnswerRe: Is this really a throttling technique? PinmemberP.J. van de Sande0:51 28 Sep '07  
GeneralGeneral throttling PinmemberBit-Smacker7:59 17 Aug '07  
Generalone small bug PinmemberFelixWatts12:16 15 Jul '07  
GeneralRe: one small bug - another one PinmemberAndrewSmith19:08 21 May '09  
GeneralThanks - I used it. PinmemberFelixWatts8:37 15 Jul '07  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120529.1 | Last Updated 3 Apr 2007
Article Copyright 2007 by P.J. van de Sande
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid