如何在进行HTTP隧道时保持连接开启

6

我连接到代理,使用“connect”命令发送一些自定义标头。这是一个要求。我得到了200响应。然后,我尝试使用相同的连接来执行get请求(在附加的代码中搜索“GET {0}”),但每次都会出现错误,最终提示“连接关闭”(无法回想起确切的错误)。基本上,我需要隧道连接到像https:\www.somesecuresite.com这样的网站。以下是代码。由于篇幅限制,某些部分被省略。

using (TcpClient client = new TcpClient(proxy, proxyPort))
            {
                using (NetworkStream stream = client.GetStream())
                {
                    string EncodedData = encodeUIDPWD(UserName, Password);
                    #region Establish Tcp tunnel

                    string reqString = "CONNECT {0}:{1} HTTP/1.1\r\nProxy-Authorization:Basic " + EncodedData + "\r\nHost: {2}:{3}\r\n";
                    reqString += "Proxy-Connection: keep-alive\r\n";
                    reqString += "Connection: keep-alive\r\n";
                    reqString += "Header1: " + header1 + "\r\n";
                    reqString += "Header2: " + header2 + "\r\n"; 
                    reqString += "None: " + None + "\r\n\r\n";

                    string rString = String.Format(reqString, myUri.Host, myUri.Port, myUri.Host, myUri.Port);
                    #endregion
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                    string reqConnectResult = await DoRequest(myUri, stream, rString);

                    lines.AddRange(reqConnectResult.Split(new string[] { Environment.NewLine }, StringSplitOptions.None).ToList());

                    if (!lines[0].Contains("200"))
                    {
                         //Error code gets caterd for here e.g 503 etc
                    }
                    else
                    {
                        foreach (string line in lines)
                        {
                            if (line.Contains("X-ProxyMesh-IP: "))
                            {
                                ip = line.Replace("X-ProxyMesh-IP: ", string.Empty);
                            }
                        }

                        string reqString1 = "GET {0} HTTP/1.1\r\nHost: {1}:{2}\r\n";
                        reqString1 += "Proxy-Connection: keep-alive\r\n";
                        reqString1 += "Connection: keep-alive\r\n\r\n";

                        string rString1 = string.Format(reqString1, myUri.PathAndQuery, myUri.Host, myUri.Port);
                        string reqPageResult = await DoRequest(myUri, stream, rString1);


                        lines.AddRange(reqPageResult.Split(new string[] { Environment.NewLine }, StringSplitOptions.None).ToList());
                        response.Content = new StringContent(lines.ToString());

                        if (lines[0].Contains("200"))
                        { 
                            return new Tuple<bool, HttpResponseMessage>(true, response);
                        }
                        else
                        {
                            return new Tuple<bool, HttpResponseMessage>(false, response);
                        }
                    }
                }
            }

 private async Task<string> DoRequest(Uri myUri, NetworkStream stream, string reqString)
{

    byte[] tunnelRequest = Encoding.UTF8.GetBytes(reqString);

    await stream.WriteAsync(tunnelRequest, 0, tunnelRequest.Length);
    await stream.FlushAsync();


    using (var memory = new MemoryStream())
    {
        await stream.CopyToAsync(memory);

        memory.Position = 0;
        var data = memory.ToArray();

        //Basically just gets the header part.
        int bm = BinaryMatch(data, Encoding.ASCII.GetBytes("\r\n\r\n"));
        var index = bm + 4;
        if (bm == -1)
        {
            index = 0;
        }

        var headers = Encoding.ASCII.GetString(data, 0, index);
        memory.Position = index;

        Console.WriteLine(headers);
        if (headers.IndexOf("Content-Encoding: gzip") > 0)
        {
            using (GZipStream decompressionStream = new GZipStream(memory, CompressionMode.Decompress))
            using (var decompressedMemory = new MemoryStream())
            {
                decompressionStream.CopyTo(decompressedMemory);
                decompressedMemory.Position = 0;
                string s = (Encoding.UTF8.GetString(decompressedMemory.ToArray()));
                Console.WriteLine(s);

                return headers + s;
            }
        }
        else
        {
            string s = (Encoding.UTF8.GetString(data, index, data.Length - index));
            Console.WriteLine(s);

            return headers + s;
        }
    }
}           

1
服务器是否响应带有“Connection: keep-alive”的标头?如果没有,那么它可能不支持它。 - Michael Coxon
1
还有没有其他原因让你手动完成这个操作而不使用 System.Net.WebRequest - Michael Coxon
1
这个可能会有帮助:https://dev59.com/aGIk5IYBdhLWcg3wke7N - Vivek Shankar
2个回答

10

Http连接因为其具有自动关闭连接的特性,会在一段时间后关闭连接,除了增加连接自动关闭时间长度(这又取决于服务器之间),你无法做太多事情,最终可能会导致连接超时。

FTP连接如果您想要上传或下载需要很长时间的数据,最好使用FTP连接,它也是出于同样的原因而存在。


6
根据您的标头的性质,您可以考虑使用WebSockets,因为您可以发送自定义授权标头。WebSocket旨在在同一连接允许全双工通信(下载和上传数据)时使用,因此比HTTP连接更合适。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接