How do you throttle the bandwidth of a socket connection in 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 中限制套接字连接的带宽?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:你如何在 C 中限制套接字连接的带宽?
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
