How to programmatically limit the download speed?

前端 未结 2 1860
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-05 01:52

I use the following code to limit the download speed of a file in java:

package org;

import java.io.IOException;
import java.io.InputStream;
import java.net         


        
2条回答
  •  独厮守ぢ
    2021-01-05 02:41

    You apparently want to limit download speed on the client side, and you also want the client to respond immediately to the connection being closed.

    AFAIK, this is not possible ... without some compromises.

    The problem is that the only way that the client application can detect that the connection is closed is by performing a read operation. That read is going to deliver data. But if you have already reached your limit for the current period, then that read will push you over the limit.

    Here are a couple of ideas:

    • If you "integrate" the download rate over a short period (e.g. 1kbytes every second versus 10kbytes every 10 seconds) then you can reduce the length of time for the sleep calls.

    • When you are close to your target download rate, you could fall back to doing tiny (e.g. 1 byte) reads and small sleeps.

    Unfortunately, both of these will be inefficient on the client side (more syscalls), but this is the cost you must pay if you want your application to detect connection closure quickly.


    In a comment you said:

    I'd expect the connection to be reset as soon as the internet connection is disabled.

    I don't think so. Normally, the client-side protocol stack will deliver any outstanding data received from the network before telling the application code that the connection it is reading has been closed.

提交回复
热议问题