使用 C# 测量 TCP 上的数据传输速率

发布于 2024-10-11 10:53:27 字数 173 浏览 9 评论 0原文

我正在使用 C# 通过 TCP 发送一个大文件,并且想测量下载速度。 如何捕获每秒的传输速率?如果我使用 IPv4InterfaceStatistics 或类似方法,我会捕获设备传输速率而不是捕获文件传输速率。 捕获设备传输速率的问题在于,它捕获通过网络设备的所有数据,而不是我传输的单个文件。

如何捕获文件传输速率?

I am sending a huge file over TCP using C#, and would like to measure the download speed.
How can I capture the transfer rate every second? If I use IPv4InterfaceStatistics or a similar method, I capture the device transfer rate instead of capturing the file transfer rate.
The problem with capturing device transfer rate is that it captures all data passing through the network device instead of the single file that I transfer.

How can I capture the file transfer rate?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

枫林﹌晚霞¤ 2024-10-18 10:53:27

由于您无法控制流来判断读取了多少数据,因此您可以在流读取之前和之后创建时间戳,然后根据接收或发送的字节数计算速度:

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块中并处理可能发生的异常。写入流和计算速度是一样的,只有这两行受到影响:

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

Since you don't have control over the stream to tell how much is read, you can create timestamps before and after a stream read and then calculate the speed based on the number of received or sent bytes:

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 block and handle exceptions that could occur. It's the same for writing to streams and calculating the speed, only these two lines are affected:

myStream.Write(buffer, 0, buffer.Length);
int speed = (buffer.Length * 8) / stopwatch.ElapsedMilliseconds; // kbps
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文