2016-04-03 61 views
0

我試圖限制每秒通過URLConnection傳輸的數據量。我爲InputStream s和OutputStream s以及使用這些流的套接字實現了一個包裝。接下來我創建了一個自定義的SocketFactory,它提供了有限的套接字。但現在的問題是,我不知道如何設置使用我的SocketFactoryURLConnection。你有什麼想法如何實現這一點?爲URLConnection實現有限帶寬

一種方法是將URLConnetion改爲使用我的節流流,但訪問由URLConnection本身使用的套接字將非常好。

回答

0

你好,這是涉及到另一個問題:How can I limit bandwidth in Java?

該解決方案易於爲我工作得很好。

//服務器代碼

Stream in; 
long timestamp = System.currentTimeInMillis(); 
int counter = 0; 
int INTERVAL = 1000; // one second 
int LIMIT = 1000; // bytes per INTERVAL 

... 

/** 
* Read one byte with rate limiting 
*/ 
@Override 
public int read() { 
    if (counter > LIMIT) { 
     long now = System.currentTimeInMillis(); 
     if (timestamp + INTERVAL >= now) { 
      Thread.sleep(timestamp + INTERVAL - now); 
     } 
     timestamp = now; 
     counter = 0; 
    } 
    int res = in.read(); 
    if (res >= 0) { 
     counter++; 
    } 
    return res; 
} 

//客戶機代碼

URL oracle = new URL("http://www.oracle.com/"); 
     URLConnection yc = oracle.openConnection(); 
     BufferedReader in = new BufferedReader(new InputStreamReader(
            yc.getInputStream())); 
     String inputLine; 
     while ((inputLine = in.readLine()) != null) 
      System.out.println(inputLine); 
     in.close(); 

的客戶端代碼源:https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html

+0

我發現,線程爲好。它幫助我實現了有限的流和套接字。但是現在我需要知道如何在URLConnection中使用這些套接字。 – CitizenVayne

+0

好的,你想爲這個URLConnection創建客戶端嗎? – jeorfevre

+0

是的,我在客戶端。我可以使用您提供的代碼創建每個時間範圍內數據有限的URLConnection。如果我可以直接以某種方式直接調用底層套接字,它仍然會很好。我打算改變分配的緩衝區大小以便在套接字上發送和接收。 – CitizenVayne