我正在尝试通过 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
我将如何使用新创建的字符集来压缩我在 main 方法中输入的字符串速度不一定是一个问题,因为我只压缩非常小的字符串对象,只要它不花费 >200 毫秒。忍受我这个压缩的东西对我来说都是很新的,如果我听起来很无知,我很抱歉。
如果我尝试仅使用 ASCII 而不是 ISO-8859-1,则字符串将压缩但不会解压缩并抛出 ZipException - 不是 GZIP 格式