如何在 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 将再次达到 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.
相关文章