2011-01-09 214 views
2

我想測量當前的下載速度。即時消息通過TCP發送大文件。我怎樣才能每秒捕獲傳輸速率?如果我使用IPv4InterfaceStatistics或類似的方法,而不是捕獲文件傳輸速率,我捕獲設備傳輸速率。捕獲設備傳輸速率的問題是它通過網絡設備捕獲所有正在進行的數據,而不是我傳輸的單個文件。用c#測量數據傳輸速率,使用tcp#

我如何捕獲文件傳輸速率?即時通訊使用C#。

+1

在接收數據的方法,檢查每一秒你有多少數據獲得和鴻溝通過。或者我在這裏錯過了一些難題? – 2011-01-09 21:06:18

+0

好吧,我如何檢查每秒有多少數據我成功地在C#中收到?也許我想念一些東西。我在networkstream找不到任何相關的方法。謝謝。 – 2011-01-09 21:11:28

回答

1

既然你沒有過流控制告訴他讀了多少,你可以在時間戳記之前和讀取,然後根據接收或發送的字節流後,計算速度:

using System.IO; 
using System.Net; 
using System.Diagnostics; 

// some code here... 

StopWatch stopWatch = new stopWatch(); 

// Begining of the loop 

int offset = 0; 
stopWatch.Reset(); 
stopWatch.Start(); 

bytes[] buffer = new bytes[1024]; // 1 KB buffer 
int actualReadBytes = myStream.Read(buffer, offset, buffer.Length); 

// Now we have read 'actualReadBytes' bytes 
// in 'stopWath.ElapsedMilliseconds' milliseconds. 

stopWatch.Stop(); 
offset += actualReadBytes; 
int speed = (actualReadBytes * 8)/stopWatch.ElapsedMilliseconds; // kbps 

// End of the loop 

您應該將Stream.Read置於try/catch並處理讀取異常。這是相同的用於寫入數據流和計算速度,僅僅這兩條線的影響:通過有時間

myStream.Write(buffer, 0, buffer.Length); 
int speed = (buffer.Length * 8)/stopWatch.ElapsedMilliseconds; // kbps