Click here to Skip to main content
15,867,568 members
Articles / Web Development / ASP.NET
Article

Bandwidth throttling

Rate me:
Please Sign up or sign in to vote.
4.75/5 (59 votes)
2 Apr 2007CPOL2 min read 273.1K   8.1K   139   61
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:

C#
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:

C#
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:

C#
...

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:

C#
...

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)


Written By
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

Comments and Discussions

 
QuestionWhy inherit from Stream? Pin
copa01730-Nov-18 2:57
copa01730-Nov-18 2:57 
QuestionWorking but sometimes its showing more speed Pin
Member 116092747-Sep-17 20:43
Member 116092747-Sep-17 20:43 
GeneralRe: Working but sometimes its showing more speed Pin
Muhammad Owais4-Oct-21 21:37
Muhammad Owais4-Oct-21 21:37 
QuestionHow to configure it using VS2015 Windows 10. Pin
Member 1291430020-Dec-16 5:29
Member 1291430020-Dec-16 5:29 
QuestionUnderstanding the bandwith usage Pin
gemese23-Apr-16 23:45
gemese23-Apr-16 23:45 
QuestionUpdated Sourcecode Pin
sx200823-Jul-15 1:20
sx200823-Jul-15 1:20 
AnswerRe: Updated Sourcecode Pin
Meixger Martin22-Jan-16 0:16
Meixger Martin22-Jan-16 0:16 
AnswerRe: Updated Sourcecode Pin
jerry_wangjh4-Feb-18 21:21
jerry_wangjh4-Feb-18 21:21 
QuestionBandwidth throttling in Task-based async methods? Pin
Alex Zelid2-Apr-14 2:54
Alex Zelid2-Apr-14 2:54 
QuestionMy vote of 5 Pin
AndyInPembs12-Dec-12 0:00
AndyInPembs12-Dec-12 0:00 
Questioncreate socket Pin
Arash Zeinoddini21-Aug-12 11:44
Arash Zeinoddini21-Aug-12 11:44 
Questionupload throttled Pin
nandobv10-Mar-12 15:10
nandobv10-Mar-12 15:10 
Generalhow to use ThrottledStream class Pin
as206em19-May-11 5:28
as206em19-May-11 5:28 
QuestionHow throttle each connection TCP/UDP? Pin
egcf21-Nov-10 11:15
egcf21-Nov-10 11:15 
If I have a list of connection TCP/UDP [see Getting active TCP/UDP connections on a box[^]], how do can limit each connection of that list using this code? I don't have idea to "intercep and limit" each connection of the list

any ideas?. Thanks!
GeneralProblems Pin
NN---21-Sep-10 2:15
NN---21-Sep-10 2:15 
GeneralBandwidth throttling Pin
commenter210-Mar-10 11:07
commenter210-Mar-10 11:07 
QuestionWhat with asp.net worker threadpool ? Pin
neoandrew7-Mar-10 14:10
neoandrew7-Mar-10 14:10 
GeneralThanks ! Pin
Ahmed Charfeddine1-Jun-09 1:17
Ahmed Charfeddine1-Jun-09 1:17 
GeneralIt works! Pin
dimpant8-May-09 14:41
dimpant8-May-09 14:41 
GeneralRe: It works! Pin
dimpant15-May-09 23:09
dimpant15-May-09 23:09 
GeneralRe: It works! Pin
Goran___20-Aug-09 2:54
Goran___20-Aug-09 2:54 
QuestionCan I adjust the bit rate on the fly? Pin
ebonnett29-Apr-09 6:22
ebonnett29-Apr-09 6:22 
AnswerRe: Can I adjust the bit rate on the fly? Pin
st0icsmitty15-Dec-09 10:25
st0icsmitty15-Dec-09 10:25 
GeneralRe: Can I adjust the bit rate on the fly? Yes... [modified] Pin
thomastmc5-Feb-10 4:04
thomastmc5-Feb-10 4:04 
GeneralIdle for a while after creating ThrottledStream constructor Pin
SchoonMan14-Oct-08 8:07
SchoonMan14-Oct-08 8:07 

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.