我开发了一个使用套接字的客户端 - 服务器聊天工具,它工作的很好,但是当我尝试使用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