URLConnection(代理代理)忽略设置代理

时间:2011-06-22 15:36:54

标签: java proxy urlconnection socks

我正在尝试测试多台计算机负载下的SOCKS代理。我的代码大纲与

类似
  1. 使用一个客户端直接连接到服务器,下载测试文件,并记录所花费的时间。
  2. 通过代理与一个客户端连接,下载测试文件,并记录花费的时间。
  3. 通过代理与多个客户端连接,下载测试文件,记录时间。
  4. 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,则withproxy忽略代理。真正奇怪的是,稍后当我尝试通过代理与多个客户端连接时,基线连接的工作方式无关紧要 - 如果基线连接没有使用代理,多个客户端连接仍然可以。

    我在这里缺少什么?

    由于

1 个答案:

答案 0 :(得分:1)

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

相关问题