5,542,300 members and growing! (17,999 online)
Email Password   helpLost your password?
General Programming » Internet / Network » Internet     Intermediate License: The Code Project Open License (CPOL)

Bandwidth throttling

By P.J. van de Sande

Save bandwidth and get QoS with bandwidth throttling.
C# 1.0, C# 2.0, C#, Windows, .NET CF, .NET, .NET 1.0, .NET 1.1, .NET 2.0, ASP.NET, VS.NET2002, VS.NET2003, VS2005, Visual Studio, Dev

Posted: 2 Apr 2007
Updated: 2 Apr 2007
Views: 28,500
Bookmarked: 53 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
33 votes for this Article.
Popularity: 6.79 Rating: 4.47 out of 5
1 vote, 3.0%
1
0 votes, 0.0%
2
2 votes, 6.1%
3
8 votes, 24.2%
4
22 votes, 66.7%
5

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


Pieter Joost is a Developer at Detrio BV. He is recently awarded as Microsoft Visual C# MVP.
Occupation: Web Developer
Location: Netherlands Netherlands

Other popular Internet / Network articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 33 (Total in Forum: 33) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralNice and idea to an improvement.memberleandrobecker11:31 25 Jul '08  
GeneralError with StreamReader.ReadLinememberMember 35721416:10 26 Jun '08  
GeneralA few changes to improve accuracy especially on a Read()memberdeepsquatter7:10 22 May '08  
GeneralExcellentmemberroyal_roi11:07 25 Mar '08  
Generalwhen will you reset time and bytecount?membertim40819:21 30 Jan '08  
GeneralIs this really a throttling technique?memberKelmen Wong0:20 28 Sep '07  
QuestionRe: Is this really a throttling technique?memberP.J. van de Sande1:51 28 Sep '07  
GeneralGeneral throttlingmemberBit-Smacker8:59 17 Aug '07  
Generalone small bugmemberFelixWatts13:16 15 Jul '07  
GeneralThanks - I used it.memberFelixWatts9:37 15 Jul '07  
QuestionI'm sorry to say the solution is NOT correctmemberSoldierQ0:02 10 Apr '07  
AnswerRe: I'm sorry to say the solution is NOT correctmemberP.J. van de Sande1:19 10 Apr '07  
GeneralRe: I'm sorry to say the solution is NOT correctmemberSoldierQ18:02 10 Apr '07  
AnswerRe: I'm sorry to say the solution is NOT correctmemberPaul A. Howes6:40 10 Apr '07  
GeneralRe: I'm sorry to say the solution is NOT correctmemberP.J. van de Sande10:23 10 Apr '07  
General5 stars codememberntorrisi9:42 4 Apr '07  
GeneralRe: 5 stars codememberP.J. van de Sande21:55 4 Apr '07  
QuestionClient Side?memberNickHD18:07 3 Apr '07  
AnswerRe: Client Side?memberP.J. van de Sande22:36 3 Apr '07  
GeneralRe: Client Side?memberBit-Smacker8:43 17 Aug '07  
Generalhelpful articlememberChristiaan van Bergen22:25 2 Apr '07  
Generalusefulmemberlxwde20:33 2 Apr '07  
GeneralRe: usefulmemberP.J. van de Sande1:36 3 Apr '07  
GeneralInteresting, but..membertkrafael_net12:03 2 Apr '07  
GeneralRe: Interesting, but..memberreinux1:28 3 Apr '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 2 Apr 2007
Editor: Smitha Vijayan
Copyright 2007 by P.J. van de Sande
Everything else Copyright © CodeProject, 1999-2008
Web16 | Advertise on the Code Project