gpt4 book ai didi

java - 如何高效压缩1025字节的json对象

转载 作者:行者123 更新时间:2023-12-02 06:32:24 27 4
gpt4 key购买 nike

我正在尝试通过 java 中的套接字连接为我正在制作的游戏发送 Json 对象(作为字符串)。该数据发送回来和第四次的速度非常快(每次传输大约 30 毫秒),我没有太多的带宽,所以我正在尽力优化我的数据传输。

这是我到目前为止接受输入并压缩它(它也解压缩)的内容,这是我的 SSCCE 我认为这是缩写?

public static void main(String[] args)
{

String compressedString = compress("{"playerX":"64","playerY":"224","playerTotalHealth":"100","playerCurrentHealth":"100","playerTotalMana":"50","playerCurrentMana":"50","playerExp":"0","playerExpTNL":"20","playerLevel":"1","points":"0","strength":"1","dexterity":"1","constitution":"1","intelligence":"1","wisdom":"1","items":["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24"],"currentMapX":"0","currentMapY":"0","playerBody":"1","playerHair":"6","playerClothes":"7"}");
System.out.println(compressedString);
System.out.println(compressedString.length());
System.out.println();
String decompressString = decompress(compressedString);
System.out.println(decompressString);
System.out.println(decompressString.length());
}

public static String compress(String str) {
String outStr = "";
try
{
if (str == null || str.length() == 0)
{
return str;
}

ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes());
gzip.close();
outStr = out.toString("ISO-8859-1");

}
catch(IOException e1)
{
e1.printStackTrace();
}
return outStr;
}

public static String decompress(String str) {
String outStr = "";
try{
if (str == null || str.length() == 0)
{
return str;
}

GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(str.getBytes("ISO-8859-1")));
BufferedReader bf = new BufferedReader(new InputStreamReader(gis, "ISO-8859-1"));

String line;
while ((line=bf.readLine())!=null)
{
outStr += line;
}

}
catch(IOException e2)
{
e2.printStackTrace();
}
return outStr;
}

我试图压缩的字符串大约有 404 个字符,它被压缩到 256 个字符。我想知道是否可以创建自己的字母表字符集和一些特殊字符,并使用它来代替所有 ISO-8859 -1

我如何使用新创建的字符集来压缩我在主方法中输入的字符串速度不一定是问题,因为我只压缩非常小的字符串对象,只要它不超过 200 毫秒。请耐心等待,这种压缩的东西对我来说是非常新鲜的,如果我听起来很无知,我很抱歉。

如果我尝试只使用 ASCII 而不是 ISO-8859-1,字符串将被压缩,但不会解压缩并抛出 ZipException - not in GZIP format

最佳答案

如果您没有足够的带宽来处理 JSON,并且您的代码库没有发生太大变化,您可能需要使用您自己的二进制编码 DataInput/OutputStream

关于java - 如何高效压缩1025字节的json对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19946360/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com