我正在尝试将压缩字节发送到另一台服务器,然后让该服务器接收它们并写出压缩文件。当我在同一台服务器上进行压缩和写入时,效果很好。本地版本如下所示:
ZipOutputStream zout = new ZipOutputStream(FileOutputStream);
zout.write(byteBuffer, 0, len);
zout.flush()
FileOutputStream.flush();
zout.close();
但是,跨服务器实现会产生错误的输出。发送代码是:(魔术字符串告诉服务器它已收到所有数据。
ZipOutputStream zout = new ZipOutputStream(out);
ZipEntry entry = new ZipEntry(fileName);
zout.putNextEntry(entry);
System.out.println("sending zipped bytes...");
zout.write(inputBuffer, contentBegin, len);
zout.flush();
zout.closeEntry();
out.flush();
byte[] magicStringData = "--------MagicStringCSE283Miami".getBytes("US-ASCII");
out.write(magicStringData, 0, magicStringData.length);
out.flush();
System.out.println("Done writing file and sending zipped bytes.");
Thread.sleep(10000);
zout.close();
clntSock.close(); // Close the socket. We are done with this client!
接收代码如下所示:
System.out.println("receiving zipped bytes...");
byte[] inputBuffer = new byte[BUF_SIZE];
int total2 = 0, count = 0;
while(count != -1) { // read from origin's buffer into byteBuffer until origin is out of data
count = inFromCompression.read(inputBuffer, total2, BUF_SIZE - total - 1);
String msg = new String(inputBuffer, total2, count, "US-ASCII");
total2 += count;
if(msg.contains("-------MagicString")){
System.out.println("full message received...");
break;
}
}
String inputString = new String(inputBuffer, 0, total2, "US-ASCII");
int contentEnd = inputString.indexOf("--------MagicString");
FileOutputStream fout2 = new FileOutputStream(outputFileName + ".zip");
fout2.write(inputBuffer, 0, contentEnd);
fout2.flush();
fout2.close();
System.out.println("Done writing zipped bytes.");
//Thread.sleep(10000);
//socketToCompression.close();
有任何想法吗?我在想这可能就像我在发送表示数据结束的魔术字符串之前没有关闭 ZipOutputStream 一样,但是每次我在刷新 zout 后立即调用 zout.close() 时,它都会关闭整个套接字。