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#.
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