項目中網絡通訊需要下載配置數據,有的數據塊非常大,比較耗時,所以想到先壓縮數據來傳輸!
因爲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));