Measure data transfer rate over tcp using c#

2019-05-27 04:46发布

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条回答
神经病院院长
2楼-- · 2019-05-27 05:44

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
查看更多
登录 后发表回答