你好,這是涉及到另一個問題: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
我發現,線程爲好。它幫助我實現了有限的流和套接字。但是現在我需要知道如何在URLConnection中使用這些套接字。 – CitizenVayne
好的,你想爲這個URLConnection創建客戶端嗎? – jeorfevre
是的,我在客戶端。我可以使用您提供的代碼創建每個時間範圍內數據有限的URLConnection。如果我可以直接以某種方式直接調用底層套接字,它仍然會很好。我打算改變分配的緩衝區大小以便在套接字上發送和接收。 – CitizenVayne