【问题标题】:URLConnection(Proxy proxy) ignoring the set proxyURLConnection(Proxy proxy) 忽略设置的代理
【发布时间】:2011-06-22 15:36:53
【问题描述】:

我正在尝试测试多台机器负载下的 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 会忽略代理。真正奇怪的是,后来当我尝试通过代理与多个客户端连接时,基线连接如何工作并不重要——如果基线连接不使用代理,多个客户端连接仍然可以。

我在这里错过了什么?

谢谢

【问题讨论】:

  • 基线是静态变量还是什么?
  • 不,每个下载实例都有自己的基线变量。

标签: java proxy urlconnection socks


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-12-06
    • 1970-01-01
    • 2020-02-02
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    相关资源
    最近更新 更多