2013-12-16 58 views
0

我有這個piede的代碼有問題,但我不能看到哪裏是錯誤做...問題與代理與插座

import java.io.*; 
import java.net.*; 
import java.util.concurrent.*; 


public class Server { 


public void startServer() { 
    final ExecutorService clientProcessingPool = Executors.newFixedThreadPool(10); 

    Runnable serverTask = new Runnable() { 
     @Override 
     public void run() { 
      try { 
       @SuppressWarnings("resource") 
       ServerSocket serverSocket = new ServerSocket(8080); 
       while (true) { 
        Socket clientSocket = serverSocket.accept(); 
        clientProcessingPool.submit(new ClientTask(clientSocket)); 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    }; 
    Thread serverThread = new Thread(serverTask); 
    serverThread.start(); 

} 

private class ClientTask implements Runnable { 
    private Socket clientSocket; 

    private ClientTask(Socket clientSocket) { 
     this.clientSocket = clientSocket; 
    } 


    @Override 
    public void run() { 

     try { 
      // Read request 
      InputStream incommingIS = clientSocket.getInputStream(); 
      byte[] b = new byte[8196]; 
      int len = incommingIS.read(b); 

      if (len > 0) { 
       System.out.println("REQUEST" 
         + System.getProperty("line.separator") + "-------"); 
       System.out.println(new String(b, 0, len)); 

       // Write request 
       Socket socket = new Socket("localhost", 8080); 
       OutputStream outgoingOS = socket.getOutputStream(); 
       outgoingOS.write(b, 0, len); 

       // Copy response 
       OutputStream incommingOS = clientSocket.getOutputStream(); 
       InputStream outgoingIS = socket.getInputStream(); 
       for (int length; (length = outgoingIS.read(b)) != -1;) { 
        incommingOS.write(b, 0, length); 
       } 

       incommingOS.close(); 
       outgoingIS.close(); 
       outgoingOS.close(); 
       incommingIS.close(); 

       socket.close(); 
      } else { 
       incommingIS.close(); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       clientSocket.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

} 

}

此代碼試圖模擬一個使用套接字的HTTP代理,代碼接收這個URL,處理它,然後再次返回瀏覽器。 問題是,瀏覽器掛起,沒有任何返回...

任何幫助將不勝感激。

謝謝。

回答

0

這不是編寫代理的正確方法。 HTTP代理接收CONNECT命令,告訴它連接到上游目標。所以你必須做的第一件事是讀一行,做上游連接,並返回一個適當的狀態。如果狀態正常,則必須啓動兩個線程才能在上游和下游之間複製字節,每個方向都有一個字符,並在收到來自兩者的EOS時關閉兩個套接字。