gpt4 book ai didi

java - URLConnection(Proxy proxy) 忽略设置的代理

转载 作者:太空宇宙 更新时间:2023-11-04 08:35:52 27 4
gpt4 key购买 nike

我正在尝试测试承受多台计算机负载的 SOCKS 代理。我的代码大纲类似于

  1. 使用一个客户端直接连接到服务器,下载测试文件,并记录所花费的时间。
  2. 通过代理与一个客户端连接,下载测试文件,并记录所花费的时间。
  3. 通过代理连接多个客户端,下载测试文件,记录时间。

1 和 2 在同一函数中执行。

private static void baseline() {
Download withProxy = new Download(socksPort, targetFile);
Download withoutProxy = new Download(true, socksPort, targetFile); //The true argument just indicates not to use the proxy.


try { //Come to think of it, I could just call run() directly here since this part is meant to be done serially.
withProxy.start();
withProxy.join();
withoutProxy.start();
withoutProxy.join();
//Some code for getting the times goes here.
} catch (Exception e) {
System.out.println("Couldn't get baseline.");
e.printStackTrace();
}
}

下载对象继承自Thread。大部分工作是在 run() 方法中完成的,如下所示:

public void run() {
try {
URL url = new URL("http://" + targetFile);
URLConnection urconn = null;
if (baseline) {
urconn = url.openConnection(Proxy.NO_PROXY);
} else {
Proxy proxy = new Proxy(Proxy.Type.SOCKS, proxyAddr);
urconn = url.openConnection(proxy);
}
InputStreamReader isr = new InputStreamReader(urconn.getInputStream());
System.out.println("Thread " + id + " is downloading.");
long startTime = System.currentTimeMillis();
char[] buf = new char[64];
while (isr.read(buf) != -1) {
;
}
long endTime = System.currentTimeMillis();
isr.close();
System.out.println("Thread " + id + " has completed.");
delta = (endTime - startTime);

} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}

问题是,当我调用基线函数时,它总是使用第一个选择的代理 - 如果我先运行 withproxy 线程,则 withoutproxy 线程将使用代理。如果我先运行 withoutproxy,withproxy 会忽略代理。真正奇怪的是,稍后当我尝试通过代理与多个客户端连接时,基线连接如何工作并不重要 - 如果基线连接不使用代理,多个客户端连接仍然使用代理。

我在这里缺少什么?

谢谢

最佳答案

我设法修复了它 - 无论出于何种原因,后续调用 url.openconnection() 之间的时间都会有所不同。在每次 start() 之间调用 Thread.sleep(10000) 有效。

关于java - URLConnection(Proxy proxy) 忽略设置的代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6442567/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com