我開發了一個使用套接字的客戶端 - 服務器聊天工具,它工作的很好,但是當我嘗試使用Deflate壓縮傳輸數據時, t工作:輸出是「空的」(實際上它不是空的,但我會在下面解釋)。使用套接字傳輸/接收壓縮數據:如何正確接收客戶端發送的數據
壓縮/解壓縮部分是100%工作(我已經測試過),所以問題必須在傳輸/接收部分的其他地方。
我使用這些方法從客戶端發送消息到服務器:
// streamOut is an instance of DataOutputStream
// message is a String
if (zip) { // zip is a boolean variable: true means that compression is active
streamOut.write(Zip.compress(message)); // Zip.compress(String) returns a byte[] array of the compressed "message"
} else {
// if compression isn't active, the client sends the not compressed message to the server (and this works great)
streamOut.writeUTF(message);
}
streamOut.flush();
我使用這些其他方法收到消息從客戶機到服務器:
// streamIn is an instace of DataInputStream
if (server.zip) { // same as before: true = compression is active
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[512];
int n;
while ((n = streamIn.read(buf)) > 0) {
bos.write(buf, 0, n);
}
byte[] output = bos.toByteArray();
System.out.println("output: " + Zip.decompress(output)); // Zip.decompress(byte[]) returns a String of decompressed byte[] array received
} else {
System.out.println("output: " + streamIn.readUTF()); // this works great
}
調試一點點我的程序,我發現while循環永遠不會結束,所以:
byte[] output = bos.toByteArray();
System.out.println("output: " + Zip.decompress(output));
永遠不會被調用。
如果我把這兩行代碼放在while循環中(在bos.write())之後,那麼一切正常(它打印從客戶端發送的消息)!但我不認爲這是解決方案,因爲接收到的byte []數組大小可能有所不同。因此,我認爲問題出在接收部分(客戶端實際上能夠發送數據)。
所以我的問題成爲接收部分的while循環。我試着用:
while ((n = streamIn.read(buf)) != -1) {
甚至與條件= 0,但它和以前一樣:循環永遠不會結束,所以輸出部分永遠不會被調用。
感謝您的意見!現在我的Zip.compress()方法在輸出byte []數組的開始處自動添加4個字節。這4個字節表示發送的壓縮消息的長度。 – HBv6 2012-07-26 08:39:13