在Unity3d中使用GZip来压缩传输数据

因为Unity中的.net支持是有限制的,所以C#自带的GZip的压缩方法不能够使用。

 

         可以到下面网址去下载一个专门的dll来处理数据的GZip压缩:

http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx

 

将下载的dll文件引入到工程中。

 

引入头部:

using ICSharpCode.SharpZipLib;
using ICSharpCode.SharpZipLib.GZip;

 

以下代码实现了压缩和解压的方法:


     MemoryStream ms = new MemoryStream();
        GZipOutputStream gzip = new GZipOutputStream(ms);
        byte[] binary = Encoding.UTF8.GetBytes("sddddddddd");
        gzip.Write(binary, 0, binary.Length);
        gzip.Close();
        byte[] press = ms.ToArray();
        Debug.Log(Convert.ToBase64String(press) + "  " + press.Length);


        GZipInputStream gzi = new GZipInputStream(new MemoryStream(press));
        
        MemoryStream re = new MemoryStream();
        int count=0;
        byte[] data=new byte[4096];
        while ((count = gzi.Read(data, 0, data.Length)) != 0)
        {
            re.Write(data,0,count);
        }
        byte[] depress = re.ToArray();
        Debug.Log(Encoding.UTF8.GetString(depress));
posted @ 2012-04-24 18:02  peiandsky  阅读(8202)  评论(0编辑  收藏  举报