你如何在 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.
相关文章