且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java HTTP 代理服务器

更新时间:2022-06-27 05:54:11

你不能把它实现为 servlet,也没有理由使用任何形式的 HTTP 客户端.

You can't implement it as a servlet, and there is no reason to use any form of HTTP client.

无功能的代理服务器是一件非常简单的事情:

A featureless proxy server is a really simple thing:

  1. 接受一个连接并为其启动一个线程.
  2. 读取来自客户端的请求直到空行.
  3. 提取 GET 或 CONNECT 命令或其他任何命令并连接到指定的主机.
  4. 如果失败,发回适当的 HTTP 错误响应,关闭套接字,然后忘记它.
  5. 否则启动两个线程来复制字节,每个方向一个.没什么好看的,就是

  1. Accept a connection and start a thread for it.
  2. Read the request from the client up to the blank line.
  3. Extract the GET or CONNECT command or whatever it is and connect to the named host.
  4. If that fails, send back an appropriate HTTP error response, close the socket, and forget about it.
  5. Otherwise start two threads to copy bytes, one in each direction. Nothing fancy, just

while ((count = in.read(buffer)) > 0)
{
    out.write(buffer, 0, count);
}

  • 当其中一个套接字读取 EOS 时,关闭另一个套接字以进行输出并退出获取 EOS 的线程.
  • 如果作为 EOS 源的套接字已经关闭以进行输出,请将它们都关闭.
  • 或者使用 Apache SQUID.

    Or use Apache SQUID.