[英]How to send compressed data using UDP or TCP (lua / java)
我正在制作一个带有 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 我尝试调整配置没有任何效果:/
我希望收到一个包含整个字符串的数据包但我收到了几个数据包,每个数据包都包含压缩字符。 例子(每一行都是服务器认为他收到一个新数据包):
(来源: noelshack.com )
经过大量研究,我最终设法解决了我的问题! 我用过这个:
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 大,所以它们只是切成两半。
假设客户端发送单个压缩“文档”,您的服务器端代码应如下所示(TCP 版本):
is = new DeflaterInputStream(clientSocket.getInputStream());
in = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String inputLine;
while ((inputLine = in.readLine()) != null) {
...
}
以上未经测试,还需要异常处理和代码以确保流始终关闭。
诀窍是您的输入管道需要在您尝试将其作为文本行读取/处理之前解压缩数据流。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.