问题描述
我正在尝试对SOCKS代理列表进行排序,并找出哪些代码的连接和读取时间小于1000毫秒,这是我的代码
I am trying to sort through a list of SOCKS proxies, and figure out which ones have a connect and read time of less than 1000ms, here is my code
for(Proxy p : proxies) {
try {
URLConnection testConnection = testUrl.openConnection(p);
testConnection.setConnectTimeout(TIMEOUT_VALUE);
testConnection.setReadTimeout(TIMEOUT_VALUE);
success.add(p);
} catch(SocketTimeoutException ste) {
System.out.println("Proxy " + p.address().toString() + " timed out.");
}
}
但他们中的每一个都通过了测试,甚至当我做 TIMEOUT_VALUE = 1;
我做错了什么?感谢您的帮助。
But every single one of them passes the test, even when I do TIMEOUT_VALUE = 1;
What am I doing wrong? Thanks for any help.
推荐答案
我认为您的问题是您没有从连接中读取任何内容。如果我将 TIMEOUT_VALUE
设置得太低,我会得到一个例外。无论我是读取所有响应还是只读一行都没有影响结果时间,我想这是因为我在一个数据包中得到了完整的答案。
I assume your problem is you don't read anything from connection. If I set TIMEOUT_VALUE
too low, I get an exception. Whether I read all response or only one line did not affect the resulting time, I guess it is because I got whole answer in one packet.
这是我使用的测量值(没有代理):
Here is the measurement I used (without proxies):
int TIMEOUT_VALUE = 1000;
try {
URL testUrl = new URL("http://google.com");
StringBuilder answer = new StringBuilder(100000);
long start = System.nanoTime();
URLConnection testConnection = testUrl.openConnection();
testConnection.setConnectTimeout(TIMEOUT_VALUE);
testConnection.setReadTimeout(TIMEOUT_VALUE);
BufferedReader in = new BufferedReader(new InputStreamReader(testConnection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
answer.append(inputLine);
answer.append("\n");
}
in.close();
long elapsed = System.nanoTime() - start;
System.out.println("Elapsed (ms): " + elapsed / 1000000);
System.out.println("Answer:");
System.out.println(answer);
} catch (SocketTimeoutException e) {
System.out.println("More than " + TIMEOUT_VALUE + " elapsed.");
}
这篇关于如何使用URLConnection超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!