asp.net實現的計算網頁下載速度的代碼

來源:互聯網
上載者:User

複製代碼 代碼如下:private void getSpeed()
{
//連結開始時間
DateTime stime = DateTime.Now;
//檔案
string url = "http://xxx.com/images/test.jpg ";
WebRequest myRequest = WebRequest.Create(url);
//連結成功
WebResponse myReponse = myRequest.GetResponse();
//取得檔案的大小 位元組單位
int ii = int.Parse(myReponse.ContentLength.ToString());
//取得流
Stream myStream = myReponse.GetResponseStream();
StreamReader sr = new StreamReader(myStream);
byte[] mbyte=new byte[ii];
int allbyte=(int)mbyte.Length;
int startbyte=0;
string test = " ";
while(ii> 0) //################ 迴圈讀取檔案,並顯示進度.....
{
int m=myStream.Read(mbyte,startbyte,allbyte);
if(m==0){break;}
startbyte+=m;
allbyte-=m;
int a1=(int)startbyte/1024;
int a2=(int)ii/1024;
test+= "串連成功..開始下載..m= "+m+ "| " + a1.ToString() + "/ " + a2.ToString() + "KB ";//startbyte + "/ " + ii.ToString();
}
//連結結束時間
DateTime etime=DateTime.Now;
TimeSpan ts = etime - stime;
//總共耗時 
double SpeedTime = (double) ts.TotalSeconds;
double Kbps = 0;
double ShowPer = 0;
if (SpeedTime> 0)
{
//網路速度
Kbps = Math.Round(Math.Round(ii*8/1024/SpeedTime*10.5)/10);
//Kbps = Math.Round(ii/1024/ SpeedTime);
}
else
{
Kbps = 10000;
}
//用來顯示當前流量所要顯示的圖片長度
ShowPer = Math.Round(Kbps/100);
if (ShowPer <1)
ShowPer = 1;
else if(ShowPer> 82)
ShowPer = 82;
//網路速度
string sp = (Math.Round(Kbps/8*10)/10).ToString();
sr.Close();
myStream.Close();
myReponse.Close();
// Response.Write(test);
Response.Write( "網路速度 "+sp+ "圖片長度$ "+ShowPer+ "耗時$ "+SpeedTime+ "檔案大小$ "+ii);
Response.End();
}

最後有網友又給出了實現的另一思路:

用一個頁面輸出一個3M的網頁(通過一個迴圈輸出位元組),然後非同步去請求這個頁面,計算開始時間與結束時間的差,然後再去計算。

思路還是老樣,就是用webRequest去擷取流檔案就只是取得回應時間,但是得不得輸出時間(自己的水平有限,不過我想肯定可以實現)。現在只是換了一個方法去擷取輸出時間。我在baidu與google也是只查到非同步擷取文字內容輸出時間可以。但是有圖片的就好像有點困難了。

不過最終的結果得到了,還是有點成績感的。呵呵。。。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.