問題描述
我正在使用 BSD 套接字編寫客戶端-服務器應用程序.它需要在后臺運行,不斷地傳輸數(shù)據(jù),但不能從正常使用中占用網(wǎng)絡(luò)接口的帶寬.根據(jù)接口的速度,我需要將此連接限制為某個最大傳輸速率.
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.
以編程方式實現(xiàn)這一目標的最佳方法是什么?
What is the best way to achieve this, programmatically?
推薦答案
每次傳輸后休眠 1 秒的問題是您的網(wǎng)絡(luò)性能會不穩(wěn)定.
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,則執(zhí)行 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%)
在每次網(wǎng)絡(luò)操作之前??或之后做一個睡眠(睡眠時間)
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.
這個解決方案很好,因為如果用戶的網(wǎng)絡(luò)已經(jīng)沒有你想要的那么高,你就不會睡覺.
This solution is good, because you will have no sleeps if the user's network is already not as high as you would like.
這篇關(guān)于你如何在 C 中限制套接字連接的帶寬?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!