Click here to Skip to main content
12,255,451 members (45,312 online)
Click here to Skip to main content
Add your own
alternative version

Stats

156.5K views
5.5K downloads
125 bookmarked
Posted

Bandwidth throttling

, 2 Apr 2007 CPOL
Rate this:
Please Sign up or sign in to vote.
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)

Share

About the Author

P.J. van de Sande
Architect Sogyo
Netherlands Netherlands
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

You may also be interested in...

Comments and Discussions

 
QuestionUnderstanding the bandwith usage Pin
gemese23-Apr-16 23:45
membergemese23-Apr-16 23:45 
QuestionUpdated Sourcecode Pin
sx200823-Jul-15 1:20
membersx200823-Jul-15 1:20 
AnswerRe: Updated Sourcecode Pin
Meixger Martin22-Jan-16 0:16
memberMeixger Martin22-Jan-16 0:16 
QuestionBandwidth throttling in Task-based async methods? Pin
Alex Zelid2-Apr-14 2:54
memberAlex Zelid2-Apr-14 2:54 
QuestionMy vote of 5 Pin
AndyInPembs12-Dec-12 0:00
memberAndyInPembs12-Dec-12 0:00 
Questioncreate socket Pin
Arash Zeinoddini21-Aug-12 11:44
memberArash Zeinoddini21-Aug-12 11:44 
Questionupload throttled Pin
nandobv10-Mar-12 15:10
membernandobv10-Mar-12 15:10 
Generalhow to use ThrottledStream class Pin
as206em19-May-11 5:28
memberas206em19-May-11 5:28 
QuestionHow throttle each connection TCP/UDP? Pin
egcf21-Nov-10 11:15
memberegcf21-Nov-10 11:15 
GeneralProblems Pin
Member 32674721-Sep-10 2:15
memberMember 32674721-Sep-10 2:15 
GeneralBandwidth throttling Pin
bidel akbari10-Mar-10 11:07
memberbidel akbari10-Mar-10 11:07 
QuestionWhat with asp.net worker threadpool ? Pin
neoandrew7-Mar-10 14:10
memberneoandrew7-Mar-10 14:10 
GeneralThanks ! Pin
Ahmed Charfeddine1-Jun-09 1:17
memberAhmed Charfeddine1-Jun-09 1:17 
GeneralIt works! Pin
dimitris.dpant8-May-09 14:41
memberdimitris.dpant8-May-09 14:41 
GeneralRe: It works! Pin
dimitris.dpant15-May-09 23:09
memberdimitris.dpant15-May-09 23:09 
GeneralRe: It works! Pin
Goran___20-Aug-09 2:54
memberGoran___20-Aug-09 2:54 
QuestionCan I adjust the bit rate on the fly? Pin
ebonnett29-Apr-09 6:22
memberebonnett29-Apr-09 6:22 
AnswerRe: Can I adjust the bit rate on the fly? Pin
st0icsmitty15-Dec-09 10:25
memberst0icsmitty15-Dec-09 10:25 
GeneralRe: Can I adjust the bit rate on the fly? Yes... [modified] Pin
thomastmc5-Feb-10 4:04
memberthomastmc5-Feb-10 4:04 
GeneralIdle for a while after creating ThrottledStream constructor Pin
SchoonMan14-Oct-08 8:07
memberSchoonMan14-Oct-08 8:07 
GeneralNice and idea to an improvement. Pin
leandrobecker25-Jul-08 10:31
memberleandrobecker25-Jul-08 10:31 
GeneralError with StreamReader.ReadLine Pin
Member 357214126-Jun-08 5:10
memberMember 357214126-Jun-08 5:10 
GeneralA few changes to improve accuracy especially on a Read() Pin
deepsquatter22-May-08 6:10
memberdeepsquatter22-May-08 6:10 
GeneralExcellent Pin
royal_roi25-Mar-08 10:07
memberroyal_roi25-Mar-08 10:07 
Questionwhen will you reset time and bytecount? Pin
tim40830-Jan-08 18:21
membertim40830-Jan-08 18:21 
QuestionIs this really a throttling technique? Pin
Kelmen Wong27-Sep-07 23:20
memberKelmen Wong27-Sep-07 23:20 
AnswerRe: Is this really a throttling technique? Pin
P.J. van de Sande28-Sep-07 0:51
memberP.J. van de Sande28-Sep-07 0:51 
GeneralGeneral throttling Pin
Bit-Smacker17-Aug-07 7:59
memberBit-Smacker17-Aug-07 7:59 
Generalone small bug Pin
FelixWatts15-Jul-07 12:16
memberFelixWatts15-Jul-07 12:16 
GeneralRe: one small bug - another one Pin
AndrewSmith21-May-09 19:08
memberAndrewSmith21-May-09 19:08 
GeneralThanks - I used it. Pin
FelixWatts15-Jul-07 8:37
memberFelixWatts15-Jul-07 8:37 
QuestionI'm sorry to say the solution is NOT correct Pin
SoldierQ9-Apr-07 23:02
memberSoldierQ9-Apr-07 23:02 
AnswerRe: I'm sorry to say the solution is NOT correct Pin
P.J. van de Sande10-Apr-07 0:19
memberP.J. van de Sande10-Apr-07 0:19 
GeneralRe: I'm sorry to say the solution is NOT correct Pin
SoldierQ10-Apr-07 17:02
memberSoldierQ10-Apr-07 17:02 
GeneralRe: I'm sorry to say the solution is NOT correct Pin
AndrewSmith21-May-09 19:12
memberAndrewSmith21-May-09 19:12 
AnswerRe: I'm sorry to say the solution is NOT correct Pin
Paul A. Howes10-Apr-07 5:40
memberPaul A. Howes10-Apr-07 5:40 
GeneralRe: I'm sorry to say the solution is NOT correct Pin
P.J. van de Sande10-Apr-07 9:23
memberP.J. van de Sande10-Apr-07 9:23 
General5 stars code Pin
ntorrisi4-Apr-07 8:42
memberntorrisi4-Apr-07 8:42 
GeneralRe: 5 stars code Pin
P.J. van de Sande4-Apr-07 20:55
memberP.J. van de Sande4-Apr-07 20:55 
QuestionClient Side? Pin
NickHD3-Apr-07 17:07
memberNickHD3-Apr-07 17:07 
AnswerRe: Client Side? Pin
P.J. van de Sande3-Apr-07 21:36
memberP.J. van de Sande3-Apr-07 21:36 
GeneralRe: Client Side? Pin
Bit-Smacker17-Aug-07 7:43
memberBit-Smacker17-Aug-07 7:43 
Generalhelpful article Pin
Christiaan van Bergen2-Apr-07 21:25
memberChristiaan van Bergen2-Apr-07 21:25 
Generaluseful Pin
lxwde2-Apr-07 19:33
memberlxwde2-Apr-07 19:33 
GeneralRe: useful Pin
P.J. van de Sande3-Apr-07 0:36
memberP.J. van de Sande3-Apr-07 0:36 
GeneralInteresting, but.. Pin
tkrafael_net2-Apr-07 11:03
membertkrafael_net2-Apr-07 11:03 
GeneralRe: Interesting, but.. Pin
reinux3-Apr-07 0:28
memberreinux3-Apr-07 0:28 
GeneralRe: Interesting, but.. Pin
P.J. van de Sande3-Apr-07 0:34
memberP.J. van de Sande3-Apr-07 0:34 
GeneralRe: Interesting, but.. Pin
reinux3-Apr-07 0:47
memberreinux3-Apr-07 0:47 
GeneralRe: Interesting, but.. Pin
P.J. van de Sande3-Apr-07 1:49
memberP.J. van de Sande3-Apr-07 1:49 

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

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

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