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 中限制套接字连接的带宽?
基础教程推荐
- 设计字符串本地化的最佳方法 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01