2010-02-16 154 views
0

我試圖壓縮和解壓縮內存流發送它通過TCP連接。 在下面的代碼中,我會在壓縮之後立即進行解壓縮,以使其首先工作。 我做了什麼我最終與一個devompressed緩衝區機智全零和在行 int read = Decompress.Read(buffie,0,buffie.Length); 似乎讀取了0個字節。壓縮和解壓在.net結束與零解壓數組

有沒有人有線索有什麼問題?

bytesRead = ms.Read(buf, 0, i); 

MemoryStream partialMs = new MemoryStream(); 
GZipStream gZip = new GZipStream(partialMs, CompressionMode.Compress); 

gZip.Write(buf, 0, buf.Length); 

partialMs.Position = 0; 

byte[] compressedBuf = new byte[partialMs.Length]; 

partialMs.Read(compressedBuf, 0, (int)partialMs.Length); 

partialMs.Close(); 

byte[] gzBuffer = new byte[compressedBuf.Length + 4]; 
System.Buffer.BlockCopy(compressedBuf, 0, gzBuffer, 4, compressedBuf.Length); 
System.Buffer.BlockCopy(BitConverter.GetBytes(buf.Length), 0, gzBuffer, 0, 4); 

using (MemoryStream mems = new MemoryStream()) 
{ 
    int msgLength = BitConverter.ToInt32(gzBuffer, 0); 

    byte[] buffie = new byte[msgLength]; 
    mems.Write(gzBuffer, 4, gzBuffer.Length - 4); 
    mems.Flush(); 
    mems.Position = 0; 

    using (GZipStream Decompress = new GZipStream(mems, CompressionMode.Decompress, true)) 
    { 
     int read = Decompress.Read(buffie, 0, buffie.Length); 
     Decompress.Close(); 
    } 
} 
+0

PS:發佈審查斷碼的預期和接受。發佈_incomplete_ _broken_代碼通常會讓你無處可尋。這就像打電話給醫生,問他你的貓有什麼問題。只是說... ;-) – 2010-02-16 08:07:37

回答

1

您的實施可能會使用一些工作。似乎有一些混淆,哪些流應該用在哪裏。這裏是工作的例子,讓你開始..在這個MSDN page


底部

看到用戶的內容

var original = new byte[65535]; 
var compressed = GZipTest.Compress(original); 
var decompressed = GZipTest.Decompress(compressed); 

using System.IO; 
using System.IO.Compression; 

public class GZipTest 
{ 
    public static byte[] Compress(byte[] uncompressedBuffer) 
    { 
     using (var ms = new MemoryStream()) 
     { 
      using (var gzip = new GZipStream(ms, CompressionMode.Compress, true)) 
      { 
       gzip.Write(uncompressedBuffer, 0, uncompressedBuffer.Length); 
      } 
      byte[] compressedBuffer = ms.ToArray(); 
      return compressedBuffer; 
     } 
    } 

    public static byte[] Decompress(byte[] compressedBuffer) 
    { 
     using (var gzip = new GZipStream(new MemoryStream(compressedBuffer), CompressionMode.Decompress)) 
     { 
      byte[] uncompressedBuffer = ReadAllBytes(gzip); 
      return uncompressedBuffer; 
     } 
    } 

    private static byte[] ReadAllBytes(Stream stream) 
    { 
     var buffer = new byte[4096]; 
     using (var ms = new MemoryStream()) 
     { 
      int bytesRead = 0; 
      do 
      { 
       bytesRead = stream.Read(buffer, 0, buffer.Length); 
       if (bytesRead > 0) 
       { 
        ms.Write(buffer, 0, bytesRead); 
       } 
      } while (bytesRead > 0); 

      return ms.ToArray(); 
     } 
    } 
} 
1

你不關閉GzipStream你寫,所以它可能是所有緩衝。我建議你在寫完數據後關閉它。

順便說一下,您可以比當前代碼更容易地從MemoryStream中獲取數據:使用MemoryStream.ToArray

+0

你是對的,喬恩,仔細看看發佈的代碼將揭示一些更基本的問題。 – 2010-02-16 08:09:28