Saturday, April 12, 2008

Bandwidth Meter for Web Application

Article described how to create Bandwidth meter to measure network bandwidth for your web application.

One of the client requested to have a Bandwidth meter for his web application. It was a big challenge to make a bandwidth meter in a browser. After thinking several hours I got an idea to make it using javascript. Here I will share my code to make bandwidth meter using javascript.

When a page is rendered to the browser it send stream of text from the server. Taking this idea i had used javascript and measured time to transfer dummy text of some size. Then I actually convert this time into bandwidth.

Below are few steps to create bandwidth meter using javascript.

1) Take starting time before transfering dummy text

<script language="javascript" type="text/javascript">
time = new Date();
time1 = time.getTime();

2) Transfer dummy text of 45000 bytes in HTML comment tag. Because we don't have to show this text to user. We are actually using this text to measure time to transfer 45000 bytes to the browser.

3) Here comes real stuff. Now we have start time before transfering 45000 bytes and current time, here calculate time difference which was actually taken to transfer 45000 bytes. Using this time difference calculate actuall bandwidth used to transfer 45000 bytes. Thats it now you are done with your own bandwidth meter :)

<script language="javascript" type="text/javascript">
time = new Date();
time2 = time.getTime();
ttime = time2 - time1;

if (ttime == 0)
ttime = .1;

ttime = ttime / 1000; //thousand mili seconds
kbps = 45 / ttime;
kbps = kbps * 8; // multiply by 8 to make kiloBITS instead of kiloBYTES
kbps = Math.round (kbps);
document.getElementById("lblBandwidth").innerHTML=kbps + " kbps";