有一些很好的庫,如this from Apache,但這對我的目的來說有點太複雜。我需要的只是獲得HTTP延遲的最佳估計值(無論傳輸速度如何,與服務器連接所需的時間)。測試HTTP延遲的短代碼?
我嘗試HTTP連接代碼this answer:
private void doPing() {
//Remember time before connection
long millis = System.currentTimeMillis();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"))) {
//We don't need any data
reader.close();
//Times is the array where we store our results
times.add((int)(System.currentTimeMillis()-millis));
//I see lot's of these in console, so it's probably working
System.out.println("Request done...");
}
//If internet is dead, does it throw exception?
catch(Exception e) {
times.add(-1);
}
}
的事情是,我不敢肯定我是什麼測量。通過價值循環給了我這個結果:
Testing connection to http://www.seznam.cz
Threads: 5
Loops per thread: 50
Given up waiting for results.
Average time to connection: 53.8 [ms]
Failures: 0.0%
Testing connection to http://www.seznam.cz
Threads: 5
Loops per thread: 100
Average time to connection: 43.58 [ms]
Failures: 0.0%
Testing connection to http://www.seznam.cz
Threads: 5
Loops per thread: 400
Average time to connection: 30.145 [ms]
Failures: 0.0%
Testing connection to http://www.stackoverflow.com
Threads: 5
Loops per thread: 30
Given up waiting for results.
Average time to connection: 4006.1111111111113 [ms]
Failures: 0.0%
Testing connection to http://www.stackoverflow.com
Threads: 5
Loops per thread: 80
Given up waiting for results.
Average time to connection: 2098.695652173913 [ms]
Failures: 0.0%
Testing connection to http://www.stackoverflow.com
Threads: 5
Loops per thread: 200
Given up waiting for results.
Average time to connection: 0.0 [ms]
//Whoops, connection dropped again
Failures: 100.0%
//Some random invalid url
Testing connection to http://www.sdsfdser.tk/
Threads: 4
Loops per thread: 20
Average time to connection: 0.0 [ms]
Failures: 100.0%
不僅如此,我不敢肯定,如果我計算出我想要的東西(雖然它反映了我的經驗),我也不能肯定在非標準情況下什麼happes。
- URL處理超時嗎?
- 它會在超時時拋出異常嗎?
請記住,這個項目應該是簡單和輕量級的,你能告訴我,如果我做對了嗎?
爲什麼線程?它不必要地使事情複雜化IMO – Diego
因爲了解網絡如何處理併發連接很重要。然而,這與我是否使用線程無關。 –
爲什麼不發送ping commnad:http://stackoverflow.com/questions/8815012/how-to-run-ping-command-and-get-ping-host-summary – Szarpul