0

我正在用 c# 编写一个轻量级代理。当我解码 gzip contentEncoding 时,我注意到如果我使用较小的缓冲区大小(4096),则流的部分解码取决于输入的大小。它是我的代码中的错误还是使它工作所需的东西?我将缓冲区设置为 10 MB,它工作正常,但违背了我编写轻量级代理的目的。

 response = webEx.Response as HttpWebResponse;
 Stream input = response.GetResponseStream();
 //some other operations on response header

 //calling DecompressGzip here


private static string DecompressGzip(Stream input, Encoding e)
    {


        StringBuilder sb = new StringBuilder();

        using (Ionic.Zlib.GZipStream decompressor = new Ionic.Zlib.GZipStream(input, Ionic.Zlib.CompressionMode.Decompress))
        {
           // works okay for [1024*1024*8];
            byte[] buffer = new byte[4096];
            int n = 0;

                do
                {
                    n = decompressor.Read(buffer, 0, buffer.Length);
                    if (n > 0)
                    {
                        sb.Append(e.GetString(buffer));
                    }

                } while (n > 0);

        }

        return sb.ToString();
    }
4

1 回答 1

0

其实,我想通了。我猜使用字符串生成器会导致问题;相反,我使用了一个内存流,它运行良好。

private static string DecompressGzip(Stream input, Encoding e)
    {

        using (Ionic.Zlib.GZipStream decompressor = new Ionic.Zlib.GZipStream(input, Ionic.Zlib.CompressionMode.Decompress))
        {

            int read = 0;
            var buffer = new byte[4096];

            using (MemoryStream output = new MemoryStream())
            {
                while ((read = decompressor.Read(buffer, 0, buffer.Length)) > 0)
                {
                    output.Write(buffer, 0, read);
                }
                return e.GetString(output.ToArray());
            }


        }

    }
于 2013-09-01T17:16:44.410 回答