Measure data transfer rate over tcp using c#

孤街浪徒 提交于 2019-12-06 07:16:29

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