项目中网络通讯需要下载配置数据,有的数据块非常大,比较耗时,所以想到先压缩数据来传输!
因为Unity中的.net支持是有限制的,所以C#自带的GZip的压缩方法不能够使用。
可以到下面网址去下载一个专门的dll来处理数据的GZip压缩:
http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx
在DownLoad目录下,我们直接下载dll文件。
将下载的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));