【问题标题】:Can't get entire response from proxy C#无法从代理 C# 获得全部响应
【发布时间】:2012-11-03 22:31:21
【问题描述】:

我正在构建一个在浏览器和 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));
        }

【问题讨论】:

    标签: c# http proxy


    【解决方案1】:

    您应该检查tunnel.Client.Receiveapplication.Client.Receive 的返回值。 Receive 不保证它会读取 dataFromApp.Length 个字节

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

    PS:你也可以试试FiddlerCore写一个Http Proxy

    【讨论】:

      【解决方案2】:

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

      HTTP 定义消息,如果您正在实现 HTTP 代理,您应该熟悉 HTTP 1.1 RFC。有多种方法可以确定lenght of an HTTP message,您必须实施所有这些方法以确保您可以成功接收和发送 HTTP 消息。

      【讨论】:

        【解决方案3】:

        谢谢大家

        我已经做到了:

        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-12-29
          • 1970-01-01
          • 2020-08-25
          • 2021-07-18
          • 2018-02-20
          • 2020-12-11
          • 1970-01-01
          • 2016-10-24
          • 1970-01-01
          相关资源
          最近更新 更多