巴拉巴拉
小魔仙

服务器使用gzip, 客户端用pako

大型字符串交互


字符串交互过大可以用gzip压缩一下,但是要考虑下cpu的性能问题,在传输大小和cpu性能上大家权衡一下

服务器使用了 gzip,客户端cocos creator / 微信小程序 js/ts 端用的是pako
pako github

服务器:

    @RequestMapping("/test1001")
    @ResponseBody
    public Api test1001(HttpServletRequest request) throws IOException {
        String json = "xxxxx";
        String zip = gzip(json);
        System.out.println("压缩前大小:" + json.length());
        System.out.println("压缩后大小:" + zip.length());
        return Api.success(zip);
    }

    @RequestMapping("/test1000")
    @ResponseBody
    public Api test1000(HttpServletRequest request) throws IOException {
        String str = request.getParameter("key");
        long time = System.currentTimeMillis();

        String outStr = unGzip(str);
        System.out.println("耗时:" + (System.currentTimeMillis() - time) + "ms");
        return Api.success(outStr);
    }

    /* 解压 */
    public static String unGzip(String str) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes("ISO-8859-1"));
        GZIPInputStream gunzip = new GZIPInputStream(in);
        byte[] buffer = new byte[256];
        int n;
        while ((n = gunzip.read(buffer)) >= 0) {
            out.write(buffer, 0, n);
        }
        String outStr = out.toString("UTF-8");
        try{
            outStr = outStr.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
            outStr = URLDecoder.decode(outStr,"UTF-8");
        }catch (Exception e){
            return "";
        }
        return outStr;
    }

    /* 压缩 */
    public static String gzip(String str) throws IOException {
        if (str == null || str.length() == 0) {
            return str;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        gzip.write(str.getBytes());
        gzip.close();
        return out.toString("ISO-8859-1");
    }

微信小程序:

var _data = 'xxxxx';
var pako = require('../pako.min.js');

Page({

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // console.log("data length:", _data.length)
        encoderTest();
        // decoderTest();
    },

})

function decoderTest(){
    wx.request({
        url: 'http://127.0.0.1:8080/test1001',
        data: { },
        method: "post",
        header: { "Content-Type": "application/x-www-form-urlencoded"},
        success: res => {
            console.log(res.data)

            console.log("解码前大小:", res.data.msg.length)
            let resp = unzip(res.data.msg)
            console.log("解码后大小:", resp.length)
            console.log(resp)
        }
    })
}

function encoderTest(){
    var data = zip(_data);
    console.log(_data)
    console.log("压缩前大小:", _data.length);
    console.log("压缩后大小:", data.length);
    console.log("压缩后内容:\n", data);
    // let date_1 = encodeURIComponent(data);
    // console.log(date_1.length)

    wx.request({
        url: 'http://127.0.0.1:8080/test1000',
        data: { key: data },
        method: "post",
        header: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        success: res => {
            console.log("服务器解码回复:");
            console.log(res.data)
        }
    })
}

// 解压
function unzip(key) {
    var restored = pako.ungzip(key, { to: 'string' });
    return restored;
    // unescape(str)  --->解压后解码,防止中午乱码
    // return unescape(key);
}

// 压缩
function zip(str) {
    //escape(str)  --->压缩前编码,防止中午乱码
    var binaryString = pako.gzip(escape(str), { to: 'string' });
    return binaryString;
}

cocos creator typescript集成

1.复制pako.min.js到cocos 项目目录,并选择加载为插件

2.创建pako工具

/**
 * https://github.com/nodeca/pako
 */
const pako = window['pako']

export class PakoUtil {
    public static zip(str: string): string {
        // escape(str)  --->压缩前编码,防止中午乱码
        var binaryString: string = pako.gzip(escape(str), { to: 'string' });
        return binaryString;
    }

    // 解压
    public static unzip(key:string):string {
        var restored = pako.ungzip(key, { to: 'string' });
        return restored;
        // unescape(str)  --->解压后解码,防止中午乱码
        // return unescape(key);
    }
}

3.测试包

import { HttpUtil } from "./HttpUtil";
import { PakoUtil } from "./PakoUtil";

const {ccclass, property} = cc._decorator;

@ccclass
export default class PakoTest extends cc.Component {

    start () {
        // this.decodeTest();
        this.encoderTest();
    }

    decodeTest(){
        HttpUtil.get("test1001", {}, (state, res)=>{
            console.log(res);
            let msg = PakoUtil.unzip(res.msg);
            console.log(msg);
        })
    }

    encoderTest(){
        let str = "gzip";
        console.log("加密前长度:", str.length, "加密前文本:", str);
        let encoderStr = PakoUtil.zip(str);
        console.log("加密后长度:", encoderStr.length, "加密后文本:", encoderStr)
        HttpUtil.post("test1000", {key: encoderStr}, (state, res)=>{
            console.log("服务器返回:", res.msg)
        })
    }

    // update (dt) {}
}

4.HttpUtil

HttpUtil可以参考之前的文章
cocos creator typescript / 微信小程序 网络请求

赞(0) 打赏
如果文章对你有帮助,欢迎你来评价反馈。AgainFly » 服务器使用gzip, 客户端用pako

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
  • Q Q(选填)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏