如何在 UDP 或 TCP 上发送压缩数据(lua / java)

我正在使用 Lua 客户端和 Java 服务器搭建一个服务器。 我需要将一些数据压缩,以减少数据流量。

为了做到这一点,我使用 LibDeflate 在客户端上压缩数据

local config = {level = 1}
local compressed = LibDeflate:CompressDeflate(data, config)
UDP.send("21107"..compressed..serverVehicleID) -- 发送数据

在服务器上,我使用以下代码接收数据包(TCP)

out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream(), "UTF-8"));
String inputLine;

while ((inputLine = in.readLine()) != null) { // 等待数据
    Log.debug(inputLine); // 这是例子中打印的内容
    String[] processedInput = processInput(inputLine);
    onDataReceived(processedInput);
}

我已经尝试使用 UDP 和 TCP 发送它,问题仍然存在。 我尝试过使用 LibDeflate:CompressDeflate 和 LibDeflate:CompressZlib 我试着调整了配置 什么都不行 :/

我希望收到一个包含完整字符串的数据包 但是我收到了几个包,每个都包含已压缩的字符。例子(每一行都是服务器认为收到了一个新包): eclipse console when receiving compressed data

(图片来源:noelshack.com)

点赞
用户139985
用户139985

假设客户端发送了一个压缩后的“文档”,那么你的服务器端代码应该像这样(TCP版本):

is = new DeflaterInputStream(clientSocket.getInputStream());
in = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String inputLine;

while ((inputLine = in.readLine()) != null) {
    ...
}

上述代码未经测试,还需要异常处理和代码来确保流始终得到关闭。

关键在于在尝试将其作为文本行读取/处理之前,你的输入管道需要对数据流进行解压缩。

2019-04-10 14:11:11
用户11340571
用户11340571

经过大量研究,最终我成功解决了我的问题!我使用了以下代码:

DataInputStream in = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream()));

int count;
byte[] buffer = new byte[8192]; // or 4096, or more

while ((count = in.read(buffer)) > 0) {
    String data = new String(buffer, 0, count);
    Do something...
}

我还没有测试接收到的压缩字符串是否有效,尝试后我会更新我的帖子。

编辑:看起来它有效了。

现在唯一的问题是当数据包比缓冲区大小大时我不知道该怎么办。我希望有一种在任何情况下都能工作的方法,因为某些数据包大于8192,它们被一分为二。

2019-04-10 21:47:17