Measure data transfer rate over tcp using c#

寵の児 提交于 2019-12-22 18:45:19

问题


i want to measure current download speed. im sending huge file over tcp. how can i capture the transfer rate every second? if i use IPv4InterfaceStatistics or similar method, instead of capturing the file transfer rate, i capture the device transfer rate. the problem with capturing device transfer rate is that it captures all ongoing data through the network device instead of the single file that i transfer.

how can i capture the file transfer rate? im using c#.


回答1:


Since you doesn't have control over stream to tell him how much read, you can time-stamp before and after a stream read and then based on received or sent bytes calculate the speed:

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

You should put the Stream.Read in a try/catch and handle reading exception. It's the same for writing to streams and calculate the speed, just these two lines are affected:

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


来源:https://stackoverflow.com/questions/4641733/measure-data-transfer-rate-over-tcp-using-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!