你如何在 C 中限制套接字连接的带宽?

How do you throttle the bandwidth of a socket connection in C?(你如何在 C 中限制套接字连接的带宽?)
本文介绍了你如何在 C 中限制套接字连接的带宽?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在使用 BSD 套接字编写客户端-服务器应用程序.它需要在后台运行,不断地传输数据,但不能从正常使用中占用网络接口的带宽.根据接口的速度,我需要将此连接限制为某个最大传输速率.

I'm writing a client-server app using BSD sockets. It needs to run in the background, continuously transferring data, but cannot hog the bandwidth of the network interface from normal use. Depending on the speed of the interface, I need to throttle this connection to a certain max transfer rate.

以编程方式实现这一目标的最佳方法是什么?

What is the best way to achieve this, programmatically?

推荐答案

每次传输后休眠 1 秒的问题是您的网络性能会不稳定.

The problem with sleeping a constant amount of 1 second after each transfer is that you will have choppy network performance.

让 BandwidthMaxThreshold 为所需的带宽阈值.

Let BandwidthMaxThreshold be the desired bandwidth threshold.

令 TransferRate 为连接的当前传输速率.

Let TransferRate be the current transfer rate of the connection.

那么……

如果检测到 TransferRate > BandwidthMaxThreshold,则执行 SleepTime = 1 + SleepTime * 1.02(将睡眠时间增加 2%)

If you detect your TransferRate > BandwidthMaxThreshold then you do a SleepTime = 1 + SleepTime * 1.02 (increase sleep time by 2%)

在每次网络操作之前或之后做一个睡眠(睡眠时间)

Before or after each network operation do a Sleep(SleepTime)

如果您检测到您的 TransferRate 远低于您的 BandwidthMaxThreshold,您可以减少您的 SleepTime.或者,您可以始终随时间衰减/减少您的 SleepTime.最终您的 SleepTime 将再次达到 0.

If you detect your TransferRate is a lot lower than your BandwidthMaxThreshold you can decrease your SleepTime. Alternatively you could just decay/decrease your SleepTime over time always. Eventually your SleepTime will reach 0 again.

除了增加 2%,您还可以将 TransferRate - BandwidthMaxThreshold 之间的差值线性增加更多.

Instead of an increase of 2% you could also do an increase by a larger amount linearly of the difference between TransferRate - BandwidthMaxThreshold.

这个解决方案很好,因为如果用户的网络已经没有你想要的那么高,你就不会睡觉.

This solution is good, because you will have no sleeps if the user's network is already not as high as you would like.

这篇关于你如何在 C 中限制套接字连接的带宽?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Bring window to front -gt; raise(),show(),activateWindow() don’t work(把窗户放在前面 -raise(),show(),activateWindow() 不起作用)
How to get a list video capture devices NAMES (web cameras) using Qt (crossplatform)? (C++)(如何使用 Qt(跨平台)获取列表视频捕获设备名称(网络摄像机)?(C++))
How to compile Qt as static(如何将 Qt 编译为静态)
C++ over Qt : Controlling transparency of Labels and Buttons(C++ over Qt:控制标签和按钮的透明度)
How to know when a new USB storage device is connected in Qt?(Qt如何知道新的USB存储设备何时连接?)
What is an event loop in Qt?(Qt 中的事件循环是什么?)