0

我正在构建一个在浏览器和 squid 代理之间运行的小型 HTTP 代理。浏览器将 HTTP 请求发送到我的代理,该代理将其重定向到 squid 代理,然后我的应用程序从 squid 代理获取响应并将其返回给浏览器。

问题是我无法从代理获得完整的响应,我得到 HTTP 200 OK ...(只是响应头),但是没有正文,我必须再次调用接收方法来获取正文。但是如果我调试我的代码(这会使应用程序变慢)它会得到所有响应(响应头和正文),TCPClass 中是否有任何适当性向我表明远程服务器仍有数据要发送给我?这是我的代码:

static void Main(string[] args)
    {
        int ServerPort = 8888;
        IPAddress localHost = new IPAddress(0x0100007f);
        TcpListener listener = new TcpListener(localHost,ServerPort);
        listener.Start();
        while(true)
        {
            string requestString = "";
            String respenseString = "";
            TcpClient application = listener.AcceptTcpClient();
            string source = application.Client.RemoteEndPoint.ToString();
            byte[] dataFromApp = new byte[application.ReceiveBufferSize];
            application.Client.Receive(dataFromApp);                
            TcpClient tunnel = new TcpClient("127.0.0.1",8080);
            tunnel.Client.Send(dataFromApp);                
            while (tunnel.Client.Connected ==true)
            {
                if(tunnel.Available != 0)
                {                        
                    byte[] responseFromProxy = new byte[tunnel.ReceiveBufferSize];
                    tunnel.Client.Receive(responseFromProxy);
                    respenseString += Encoding.UTF8.GetString(responseFromProxy);
                }
                else
                {                        
                    break;
                }
            }                
            application.Client.Send(Encoding.UTF8.GetBytes(respenseString));
        }
4

3 回答 3

1

tunnel.Client.Receive您应该检查and的返回值application.Client.ReceiveReceive不保证它将读取dataFromApp.Length字节

备注:Receive方法将数据读入buffer参数,返回成功读取的字节数

PS:你可能还想试试FiddlerCore写一个 Http Proxy

于 2012-11-15T10:31:08.427 回答
0

套接字上没有“此消息剩余 N 个字节”属性,因为 TCP 套接字是流式传输的:它发送和接收字节,而不是消息。

HTTP defines messages, and if you are implementing an HTTP proxy, you should be familiar with the HTTP 1.1 RFC. There are various ways to determine the lenght of an HTTP message, all of which you have to implement to make sure you can successfully receive and send HTTP messages.

于 2012-11-15T10:42:13.307 回答
-1

Thanks guys

I've done it :

while (tunnel.Client.Receive(oneByte) != 0)
{
  byte[] responseFromProxy = new byte[tunnel.Available];
  tunnel.Client.Receive(responseFromProxy);
  application.Client.Send(oneByte);
  application.Client.Send(responseFromProxy);
}
于 2012-11-16T16:01:11.390 回答