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

问题描述 投票:1回答:2

我正在使用lua客户端和Java服务器制作服务器。我需要压缩一些数据以减少数据流量。

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

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

在服务器上我使用它来接收数据包(TCP)

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

while ((inputLine = in.readLine()) != null) { // Wait for data
    Log.debug(inputLine); // It is what get printed in the exemple
    String[] processedInput = processInput(inputLine);
    onDataReceived(processedInput);
}

我已经尝试使用UDP和TCP发送它,问题是一样的。我尝试使用LibDeflate:CompressDeflate和LibDeflate:CompressZlib我尝试调整配置Nothing工作:/

我希望收到一个包含整个字符串的数据包但我收到的数据包很少,每个数据包都包含压缩字符。例如(每行是服务器认为他收到一个新包):eclipse console when receiving compressed data http://image.noelshack.com/fichiers/2019/15/3/1554903043-annotation-2019-04-10-153025.jpg

java tcp lua udp luasocket
2个回答
1
投票

经过大量的研究,我终于设法解决了我的问题!我用过这个:

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,所以它们只被减少了一半。


0
投票

假设客户端发送单个压缩的“文档”,您的服务器端代码应该看起来像这样(TCP版本):

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

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

以上是未经测试的,还需要异常处理和代码以确保流始终关闭。

诀窍是您的输入管道需要在尝试将其作为文本行读取/处理之前解压缩数据流。

© www.soinside.com 2019 - 2024. All rights reserved.