使用C#测量TCP上的数据传输速率 [英] Measure data transfer rate over tcp using c#

查看:503
本文介绍了使用C#测量TCP上的数据传输速率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测量当前的下载速度.即时通讯通过TCP发送巨大的文件.我如何每秒捕获一次传输速率?如果我使用IPv4InterfaceStatistics或类似方法,则不是捕获文件传输速率,而是捕获设备传输速率.捕获设备传输速率的问题在于,它捕获的是通过网络设备捕获的所有正在进行的数据,而不是我传输的单个文件.

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.

如何获取文件传输速率?我正在使用c#.

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

您应该将Stream.Read放在try/catch中,并处理读取异常.写入流和计算速度是相同的,只是这两行会受到影响:

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

这篇关于使用C#测量TCP上的数据传输速率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆