[英]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.