java与unity3d通信之数据压缩

Wesley13
• 阅读 498

最近项目中java、Untiy两端通信用的json,json相对纯字节通信,数据包要大很多,这就涉及到数据压缩了。untiy客户端最早用的C#自带的压缩算法,但在untiy上用就抛出异常。而后我建议他们使用lzma开源压缩算法,原来用过,在此贴出来,记录一下。

package com.kaka.util;

import SevenZip.Compression.LZMA.Decoder;
import SevenZip.Compression.LZMA.Encoder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 7zip的lzma压缩,压缩比高,效率低
 *
 * @author zhoukai
 */
public final class Lzma {

    /**
     * lzma压缩
     *
     * @param is 压缩输入流
     * @param os 压缩后的输出流
     */
    public final static void compress(InputStream is, OutputStream os) {
        Encoder ec = new Encoder();
        try {
            ec.WriteCoderProperties(os);
            os.write(BitConverter.getBytes((long) is.available()));
            ec.Code(is, os, -1, -1, null);
        } catch (IOException ex) {
            Logger.getLogger(Lzma.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * lzma压缩
     *
     * @param is 压缩输入流
     * @return 压缩后的输出流
     */
    public final static byte[] compress(InputStream is) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        compress(is, os);
        return os.toByteArray();
    }

    /**
     * lzma压缩
     *
     * @param src 压缩输入字节数组
     * @return 压缩后的输出的字节数组
     */
    public final static byte[] compress(byte[] src) {
        return Lzma.compress(new ByteArrayInputStream(src));
    }

    /**
     * lzma压缩
     *
     * @param src 压缩输入字符串
     * @return 压缩后的输出的字节数组
     */
    public final static byte[] compress(String src) {
        return Lzma.compress(src.getBytes(Charset.utf8));
    }

    /**
     * lzma压缩
     *
     * @param src 压缩输入字符串
     * @param charset 字符串转字节的编码
     * @return 压缩后的输出的字节数组
     */
    public final static byte[] compress(String src, String charset) {
        byte[] bytes = null;
        try {
            bytes = src.getBytes(charset);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Lzma.class.getName()).log(Level.SEVERE, null, ex);
        }
        return Lzma.compress(bytes);
    }

    /**
     * lzma压缩
     *
     * @param src 压缩输入字符串
     * @param charset 字符串转字节的编码
     * @return 压缩后的输出的字节数组
     */
    public final static byte[] compress(String src, java.nio.charset.Charset charset) {
        byte[] bytes = src.getBytes(charset);
        return Lzma.compress(bytes);
    }

    /**
     * lzma解压缩
     *
     * @param is 解压缩输入流
     * @param os 解压缩后的输出流
     */
    public final static void uncompress(InputStream is, OutputStream os) {
        Decoder dc = new Decoder();
        int propertiesSize = 5;
        byte[] properties = new byte[propertiesSize];
        try {
            if (is.read(properties, 0, propertiesSize) != propertiesSize) {
                throw new Exception("input .lzma file is too short");
            }
            if (!dc.SetDecoderProperties(properties)) {
                throw new Exception("Incorrect stream properties");
            }
            byte[] outSizeBytes = new byte[8];
            is.read(outSizeBytes, 0, outSizeBytes.length);
            long outSize = BitConverter.toLong(outSizeBytes, 0);
            dc.Code(is, os, outSize);
        } catch (Exception ex) {
            Logger.getLogger(Lzma.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * lzma解压缩
     *
     * @param is 解压缩输入流
     * @return 解压缩后的输出字节数组
     */
    public final static byte[] uncompress(InputStream is) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            uncompress(is, os);
        } catch (Exception ex) {
            Logger.getLogger(Lzma.class.getName()).log(Level.SEVERE, null, ex);
        }
        return os.toByteArray();
    }

    /**
     * lzma解压缩
     *
     * @param src 解压缩输入字节数组
     * @return 解压缩后的输出字节数组
     */
    public final static byte[] uncompress(byte[] src) {
        return Lzma.uncompress(new ByteArrayInputStream(src));
    }
}

C#客户端代码

using System;
using System.IO;
using SevenZip.Compression.LZMA;

public class Lzma {

    private static void Compress(Stream input, Stream output)
    {
        input.Position = 0;
        Encoder ec = new Encoder();
        ec.WriteCoderProperties(output);
        byte[] lenBytes = BitConverter.GetBytes((long)input.Length);
        if(BitConverter.IsLittleEndian)
        {
            Array.Reverse(lenBytes);
        }
        output.Write(lenBytes, 0, lenBytes.Length);
        ec.Code(input, output, -1, -1, null);
    }

    public static byte[] Compress(byte[] src)
    {
        Stream input = new MemoryStream(src);
        Stream output = new MemoryStream();
        Compress(input, output);
        output.Position = 0;
        byte[] bytes = new byte[output.Length];
        output.Read(bytes, 0, bytes.Length);
        input.Close();
        output.Flush();
        output.Close();
        return bytes;
    }

    public static byte[] CompressToUTF8Bytes(string src)
    {
        return Compress(System.Text.Encoding.UTF8.GetBytes(src));
    }

    private static void Uncompress(Stream input, Stream output)
    {
        input.Position = 0;
        Decoder dc = new Decoder();
        int propertiesSize = 5;
        byte[] properties = new byte[propertiesSize];
        if (input.Read(properties, 0, propertiesSize) != propertiesSize)
        {
            throw new Exception("input .lzma file is too short");
        }
        dc.SetDecoderProperties(properties);
        byte[] outSizeBytes = new byte[8];
        input.Read(outSizeBytes, 0, outSizeBytes.Length);
        if (BitConverter.IsLittleEndian)
        {
            Array.Reverse(outSizeBytes);
        }
        long outSize = BitConverter.ToInt64(outSizeBytes, 0);
        dc.Code(input, output, -1, outSize, null);
    }

    public static byte[] Uncompress(byte[] src)
    {
        Stream input = new MemoryStream(src);
        Stream output = new MemoryStream();
        Uncompress(input, output);
        output.Position = 0;
        byte[] bytes = new byte[output.Length];
        output.Read(bytes, 0, bytes.Length);
        input.Close();
        output.Flush();
        output.Close();
        return bytes;
    }

    public static string UncompressToUTF8String(byte[] src)
    {
        return System.Text.Encoding.UTF8.GetString(Uncompress(src));
    }

}

测试的时候,使用Lzma进行数据压缩压测效率不是很好,后面客户端人员发现了ICSharpCode.SharpZipLib这个库,于是又测试了一下gzip算法,还好java有点积累,工具类有现成的

package com.kaka.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * GZIP压缩,压缩比相对lzma较低,但压缩效率高
 *
 * @author zhoukai
 */
public final class GZip {

    /**
     * 压缩数据
     *
     * @param is 数据源
     * @param os 压缩后的数据
     */
    public final static void compress(InputStream is, OutputStream os) {
        try (GZIPOutputStream gos = new GZIPOutputStream(os)) {
            int count;
            byte data[] = new byte[256];
            while ((count = is.read(data, 0, 256)) != -1) {
                gos.write(data, 0, count);
            }
            gos.finish();
            gos.flush();
        } catch (Exception ex) {
            Logger.getLogger(GZip.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * 压缩
     *
     * @param src 压缩源
     * @return 压缩后的输出的字节数组
     */
    public final static byte[] compress(byte[] src) {
        if (src == null) {
            return null;
        }
        if (src.length == 0) {
            return src;
        }
        byte[] bytes = null;
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            try (GZIPOutputStream zip = new GZIPOutputStream(out)) {
                zip.write(src);
                zip.finish();
                zip.flush();
            }
            bytes = out.toByteArray();
        } catch (IOException ex) {
            Logger.getLogger(GZip.class.getName()).log(Level.SEVERE, null, ex);
        }
        return bytes;
    }

    /**
     * gzip压缩
     *
     * @param src 压缩输入字符串
     * @param charset 字符串转字节的编码
     * @return 压缩后的输出的字节数组
     */
    public final static byte[] compress(String src, String charset) {
        byte[] bytes = null;
        try {
            bytes = src.getBytes(charset);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Lzma.class.getName()).log(Level.SEVERE, null, ex);
        }
        return compress(bytes);
    }

    /**
     * gzip压缩
     *
     * @param src 压缩输入字符串
     * @param charset 字符串转字节的编码
     * @return 压缩后的输出的字节数组
     */
    public final static byte[] compress(String src, java.nio.charset.Charset charset) {
        byte[] bytes = src.getBytes(charset);
        return compress(bytes);
    }

    /**
     * 解压缩
     *
     * @param src
     * @return
     */
    public final static byte[] uncompress(byte[] src) {
        if (src == null) {
            return null;
        }
        if (src.length == 0) {
            return src;
        }
        try (ByteArrayInputStream in = new ByteArrayInputStream(src)) {
            try (GZIPInputStream zip = new GZIPInputStream(in)) {
                byte[] bytes;
                try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
                    int count;
                    bytes = new byte[256];
                    while ((count = zip.read(bytes, 0, bytes.length)) != -1) {
                        os.write(bytes, 0, count);
                    }
                    bytes = os.toByteArray();
                }
                return bytes;
            }
        } catch (IOException ex) {
            Logger.getLogger(GZip.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
}

C# gzip工具类

using System.IO;
using ICSharpCode.SharpZipLib.GZip;


public class GZip {

    public static byte[] Compress(byte[] src)
    {
        MemoryStream ms = new MemoryStream();
        GZipOutputStream gzip = new GZipOutputStream(ms);
        gzip.Write(src, 0, src.Length);
        gzip.Close();
        byte[] bytes =  ms.ToArray();
        ms.Close();
        return bytes;
    }

    public static byte[] Uncompress(byte[] src)
    {
        MemoryStream ms = new MemoryStream(src);
        GZipInputStream gzip = new GZipInputStream(ms);
        MemoryStream re = new MemoryStream();
        int count = 0;
        byte[] data = new byte[2048];
        while ((count = gzip.Read(data, 0, data.Length)) != 0)
        {
            re.Write(data, 0, count);
        }
        byte[] depress = re.ToArray();
        ms.Close();
        re.Close();
        gzip.Close();
        return depress;
    }

    public static byte[] CompressToUTF8Bytes(string src)
    {
        return Compress(System.Text.Encoding.UTF8.GetBytes(src));
    }

    public static string UncompressToUTF8String(byte[] src)
    {
        return System.Text.Encoding.UTF8.GetString(Uncompress(src));
    }

}
点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Karen110 Karen110
2年前
一篇文章带你了解JavaScript日期
日期对象允许您使用日期(年、月、日、小时、分钟、秒和毫秒)。一、JavaScript的日期格式一个JavaScript日期可以写为一个字符串:ThuFeb02201909:59:51GMT0800(中国标准时间)或者是一个数字:1486000791164写数字的日期,指定的毫秒数自1970年1月1日00:00:00到现在。1\.显示日期使用
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Wesley13 Wesley13
2年前
Java获得今日零时零分零秒的时间(Date型)
publicDatezeroTime()throwsParseException{    DatetimenewDate();    SimpleDateFormatsimpnewSimpleDateFormat("yyyyMMdd00:00:00");    SimpleDateFormatsimp2newS
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这