我想在客户端解压缩从服务器发送的包。
当包的大小很小时,下面的代码就可以了。
但是,当包的大小较大时,out_length 变量的值必须大于 1024。我不想这样做,我想有一个动态的方式。这意味着当包裹的尺寸更大时,我不必更改out_length!请帮我。
int Decompress(BYTE *src, int srcLen, BYTE *dst)
{
static char dummy_head[2] =
{
0x8 + 0x7 * 0x10,
(((0x8 + 0x7 * 0x10) * 0x100 + 30) / 31 * 31) & 0xFF,
};
int out_length = 1024;
z_stream strm;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.next_in = (Bytef *)src;
strm.avail_in = srcLen;
strm.next_out = (Bytef *)dst;
strm.avail_out = out_length;
/** 15 window bits, and the +32 tells zlib to to detect if using gzip or zlib **/
int ret = inflateInit2(&strm, 15 + 32);
if (ret != Z_OK)
{
return -1;
}
while (strm.total_out < out_length && strm.total_in < srcLen)
{
/* force small buffers */
strm.avail_in = strm.avail_out = 1;
if((ret = inflate(&strm, Z_NO_FLUSH)) == Z_STREAM_END)
{
break;
}
if(ret != Z_OK )
{
if(ret == Z_DATA_ERROR)
{
strm.next_in = (Bytef*) dummy_head;
strm.avail_in = sizeof(dummy_head);
if((ret = inflate(&strm, Z_NO_FLUSH)) != Z_OK)
{
return -1;
}
}
else
{
return -1;
}
}
}
// realease the memory for z_stream
if (inflateEnd(&strm) != Z_OK)
{
return -1;
}
return strm.total_out;
}