使用套接字编写代理

时间:2013-12-07 00:52:42

标签: java sockets proxy

我正在使用套接字编写HTTP代理服务器,现在程序正在成功接收请求,但我无法再将其恢复到浏览器...

import java.io.*;
import java.net.*;
import java.util.List;
import java.util.Map;
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(80);
                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", 80);
                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();
            }
        }
    }

}

}

我做错了什么?有人可以帮我吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

您假设您在一次读取中获得了整个请求,而不是像响应循环那样使用循环。

您还假设它被流结束终止,这意味着客户端必须完成shutdownOutput(),这在大多数协议中都不会发生。

通常,这不是编写代理的正确技术。您需要为每个客户端启动两个线程,同时在两个方向上复制数据,并推迟关闭套接字,直到您从两个方向读取EOS。