有一些很好的库,如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