c - 在zlib.h中使用inflate在client中使用server发送的解压包时初始化z_stream.avail_out的值

标签 c client-server zlib inflate

我想在客户端解压服务器发过来的包。

当包的尺寸较小时,下面的代码就可以了。

但是当包的尺寸较大时,下面的 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;
}

最佳答案

this example了解如何将 inflate() 与固定大小的缓冲区一起使用。如果我明白你在问什么,该示例会重复使用相同的输出缓冲区,直到所有数据都被解压缩。然后你每次都必须对输出缓冲区中的未压缩数据做一些事情,因为它会在下一次被覆盖。您的 Decompress() 函数不会对未压缩的数据执行任何操作。

关于c - 在zlib.h中使用inflate在client中使用server发送的解压包时初始化z_stream.avail_out的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18082774/

相关文章:

vb.net - TCP客户端到服务器通信

zlib - 找不到 ZLIB(缺少 : ZLIB_LIBRARY) (found version "1.2.11")

c - 测量缓存延迟

c - 值既不是数组也不是指针

c# - mono_field_set_value 不起作用

c - 获取段错误(核心转储)

java - 简单的客户端-服务器在 Java 中相互通信

java - ServerSocket java-server 只读取输入一次?

ios - 在 Swift2 中使用 iOS9 压缩框架

c - zlib 压缩和解压使用