场景

1.一般在使用文本json传输数据, 数据量特别大时,传输的过程就特别耗时, 因为带宽或者socket的缓存是有限制的, 数据量越大, 传输时间就越长. 网站一般使用gzip来压缩成二进制.

说明

1.zlib库可以实现gzip和zip方式的压缩, 这里只介绍zip方式的二进制压缩, 压缩比还是比较可观的, 一般写客户端程序已足够.

2.修改了一下zpipe.c的实现, 其实就是把读文件改为读字符串, 写文件改为写字符串即可.

例子


// test_zlib.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

#include <string>
#include <iostream>
#include <memory>
#include <assert.h>
#include "zlib.h"

// E:\software\Lib\compress\zlib-1.2.5\src\examples
// zpipe.c

#define CHUNK 16384

/* Compress from file source to file dest until EOF on source.
   def() returns Z_OK on success, Z_MEM_ERROR if memory could not be
   allocated for processing, Z_STREAM_ERROR if an invalid compression
   level is supplied, Z_VERSION_ERROR if the version of zlib.h and the
   version of the library linked do not match, or Z_ERRNO if there is
   an error reading or writing the files. */
int CompressString(const char* in_str,size_t in_len,
    std::string& out_str, int level)
{
    if(!in_str)
        return Z_DATA_ERROR;

    int ret, flush;
    unsigned have;
    z_stream strm;

    unsigned char out[CHUNK];

    /* allocate deflate state */
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    strm.opaque = Z_NULL;
    ret = deflateInit(&strm, level);
    if (ret != Z_OK)
        return ret;

    std::shared_ptr<z_stream> sp_strm(&strm,[](z_stream* strm){
         (void)deflateEnd(strm);
    });
    const char* end = in_str+in_len;

    size_t pos_index = 0;
    size_t distance = 0;
    /* compress until end of file */
    do {
        distance = end - in_str;
        strm.avail_in = (distance>=CHUNK)?CHUNK:distance;
        strm.next_in = (Bytef*)in_str;

        // next pos
        in_str+= strm.avail_in;
        flush = (in_str == end) ? Z_FINISH : Z_NO_FLUSH;

        /* run deflate() on input until output buffer not full, finish
           compression if all of source has been read in */
        do {
            strm.avail_out = CHUNK;
            strm.next_out = out;
            ret = deflate(&strm, flush);    /* no bad return value */
            if(ret == Z_STREAM_ERROR)
                break;
            have = CHUNK - strm.avail_out;
            out_str.append((const char*)out,have);
        } while (strm.avail_out == 0);
        if(strm.avail_in != 0);     /* all input will be used */
            break;

        /* done when last data in file processed */
    } while (flush != Z_FINISH);
    if(ret != Z_STREAM_END)  /* stream will be complete */
        return Z_STREAM_ERROR;

    /* clean up and return */
    return Z_OK;
}

/* Decompress from file source to file dest until stream ends or EOF.
   inf() returns Z_OK on success, Z_MEM_ERROR if memory could not be
   allocated for processing, Z_DATA_ERROR if the deflate data is
   invalid or incomplete, Z_VERSION_ERROR if the version of zlib.h and
   the version of the library linked do not match, or Z_ERRNO if there
   is an error reading or writing the files. */
int DecompressString(const char* in_str,size_t in_len, std::string& out_str)
{
    if(!in_str)
        return Z_DATA_ERROR;

    int ret;
    unsigned have;
    z_stream strm;
    unsigned char out[CHUNK];

    /* allocate inflate state */
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    strm.opaque = Z_NULL;
    strm.avail_in = 0;
    strm.next_in = Z_NULL;
    ret = inflateInit(&strm);
    if (ret != Z_OK)
        return ret;

    std::shared_ptr<z_stream> sp_strm(&strm,[](z_stream* strm){
         (void)inflateEnd(strm);
    });

    const char* end = in_str+in_len;

    size_t pos_index = 0;
    size_t distance = 0;

    int flush = 0;
    /* decompress until deflate stream ends or end of file */
    do {
        distance = end - in_str;
        strm.avail_in = (distance>=CHUNK)?CHUNK:distance;
        strm.next_in = (Bytef*)in_str;

        // next pos
        in_str+= strm.avail_in;
        flush = (in_str == end) ? Z_FINISH : Z_NO_FLUSH;

        /* run inflate() on input until output buffer not full */
        do {
            strm.avail_out = CHUNK;
            strm.next_out = out;
            ret = inflate(&strm, Z_NO_FLUSH);
            if(ret == Z_STREAM_ERROR)  /* state not clobbered */
                break;
            switch (ret) {
            case Z_NEED_DICT:
                ret = Z_DATA_ERROR;     /* and fall through */
            case Z_DATA_ERROR:
            case Z_MEM_ERROR:
                return ret;
            }
            have = CHUNK - strm.avail_out;
            out_str.append((const char*)out,have);
        } while (strm.avail_out == 0);

        /* done when inflate() says it's done */
    } while (flush != Z_FINISH);

    /* clean up and return */
    return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
}

int _tmain(int argc, _TCHAR* argv[])
{
    const char* buf  = "01010101010101010101010000000000000000000000000000011111111111111"
        "01010101010101010101010000000000000000000000000000011111111111111"
        "01010101010101010101010000000000000000000000000000011111111111111"
        "01010101010101010101010000000000000000000000000000011111111111111"
        "01010101010101010101010000000000000000000000000000011111111111111"
        "01010101010101010101010000000000000000000000000000011111111111111"
        "01010101010101010101010000000000000000000000000000011111111111111"
        "01010101010101010101010000000000000000000000000000011111111111111"
        "01010101010101010101010000000000000000000000000000011111111111111"
        "01010101010101010101010000000000000000000000000000011111111111111"
        "qwertyuiop[]";

    std::cout << "========= CompressString ===========" << std::endl;
    std::cout << "Source Buffer Size: " << strlen(buf) << std::endl;
    std::string out_compress;
    assert(CompressString(buf,strlen(buf),out_compress,Z_DEFAULT_COMPRESSION) == Z_OK);
    std::cout << "Compress Buffer Size: " << out_compress.size() << std::endl;

    std::cout << "========= DecompressString ===========" << std::endl;
    std::string out_decompress;
    assert(DecompressString(out_compress.c_str(),out_compress.size(),out_decompress) == Z_OK);
    std::cout << "Decompress Buffer Size: " << out_decompress.size() << std::endl;
    assert(!out_decompress.compare(buf));

    return 0;
}

输出:

========= CompressString ===========
Source Buffer Size: 662
Compress Buffer Size: 38
========= DecompressString ===========
Decompress Buffer Size: 662

参考

zlib\src\examples\zpipe.c

C++ Code Snippet - Compressing STL Strings with zlib

[Zlib]_[初级]_[使用zlib库压缩和解压STL string]的更多相关文章

  1. C#文件或文件夹压缩和解压方法(通过ICSharpCode.SharpZipLib.dll)

    我在网上收集一下文件的压缩和解压的方法,是通过ICSharpCode.SharpZipLib.dll 来实现的 一.介绍的目录 第一步:下载压缩和解压的 ICSharpCode.SharpZipLib ...

  2. 黄聪:.NET中zip的压缩和解压——SharpCompress

    使用Packaging无法实现通用的zip(使用其他工具压缩)的解压,只支持通过Packaging压缩包zip的解压,而SharpZipLib是基于“GPL”开源方式,风险比较大.在codeplex找 ...

  3. [Swift通天遁地]七、数据与安全-(9)文件的压缩和解压

    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs. ...

  4. C#压缩和解压文件

    这里用两种方法实现C#压缩和解压文件 1.使用System.IO.Compression名称空间下的相关类(需引用 System.IO.Compression.FileSystem和System.IO ...

  5. 【C#公共帮助类】WinRarHelper帮助类,实现文件或文件夹压缩和解压,实战干货

    关于本文档的说明 本文档使用WinRAR方式来进行简单的压缩和解压动作,纯干货,实际项目这种压缩方式用的少一点,一般我会使用第三方的压缩dll来实现,就如同我上一个压缩类博客,压缩的是zip文件htt ...

  6. java 文件压缩和解压(ZipInputStream, ZipOutputStream)

    最近在看java se 的IO 部分 , 看到 java 的文件的压缩和解压比较有意思,主要用到了两个IO流-ZipInputStream, ZipOutputStream,不仅可以对文件进行压缩,还 ...

  7. C#实现通过Gzip来对数据进行压缩和解压

    C#实现通过Gzip来对数据进行压缩和解压 internal static byte[] Compress(byte[] data) { using (var compressedStream = n ...

  8. linux常用命令:4文件压缩和解压命令

    文件压缩和解压命令 压缩命令:gzip.tar[-czf].zip.bzip2 解压缩命令:gunzip.tar[-xzf].unzip.bunzip2 1. 命令名称:gzip 命令英文原意:GNU ...

  9. .net文件压缩和解压及中文文件夹名称乱码问题

    /**************************注释区域内为引用http://www.cnblogs.com/zhaozhan/archive/2012/05/28/2520701.html的博 ...

随机推荐

  1. 【SPL标准库专题(7)】 Datastructures:SplHeap & SplMaxHeap & SplMinHeap

    堆(Heap)就是为了实现优先队列而设计的一种数据结构,它是通过构造二叉堆(二叉树的一种)实现.根节点最大的堆叫做最大堆或大根堆,根节点最小的堆叫做最小堆或小根堆.二叉堆还常用于排序(堆排序). 类摘 ...

  2. .NET实现自动编译

    前言 因每次发布版本的时候,都需要打开vs项目,然后进行编译.如果刚好手里有文件在修改,就需要先签入之类的.所以想找个可以实现自动编译的工具. 在网上查询了不少资料,终于基本上实现了自动编译的功能.因 ...

  3. Python中则正则表达式

    http://blog.csdn.net/carolzhang8406/article/details/6335072 http://www.iteedu.com/plang/python/pyred ...

  4. nc 命令使用详解

    nc 命令介绍: Ncat is a feature-packed networking utility which reads and writes data across networks fro ...

  5. 安全之路 —— 利用SVCHost.exe系统服务实现后门自启动

    简介 在Windows系统中有一个系统服务控制器,叫做SVCHost.exe,它可以用来管理系统的多组服务.它与普通的服务控制不同的是它采用dll导出的ServiceMain主函数实现服务运行,详细原 ...

  6. 自己动手制作一个本地的yum仓库

    制作本地yum源有两种方式,第一种是使用光盘镜像,然后在本地进行安装.第二种是我们自己创建一个本地yum仓库,然后使用file的形式来向本地提供yum repo(也可以使用http的方式向外部提供,我 ...

  7. 高斯消去、追赶法 matlab

    1. 分别用Gauss消去法.列主元Gauss消去法.三角分解方法求解方程组 程序: (1)Guess消去法: function x=GaussXQByOrder(A,b) %Gauss消去法 N = ...

  8. mysql用户管理与权限

    1.设置密码 set password for 用户名@localhost = password('密码'); 2.取消密码 set password for 用户名@localhost = pass ...

  9. DevExpress11、TreeList

    一.简介 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; ...

  10. 【2017下集美大学软工1412班_助教博客】个人作业2——APP案例分析

    作业要求 个人作业2:APP案例分析 评分结果 按从高到低排列 学号后三位 第二次作业 Total 008 APP案例分析 23 044 第2次作业 19.5 011 App案例分析--XBMC 19 ...