今天遇到个错误是关于GZIPInPutStream压缩流的问题。
一直会爆错:Unexpected end of ZLIB input stream
说未找到正确结束符。
这个错误跟踪就是在我解压缩的地方,
这地方试了好几种流也没搞定,后来我就以为服务端Socket发送数据时候出了问题,一直测也没出来结果,最后还是有个同事,仔细看了他自己写的东西,经过修改大半天,发现是网络流传过来的时候没读完整导致这问题出现了。
这样的错增长了一次见识,记录下来
一直会爆错:Unexpected end of ZLIB input stream
说未找到正确结束符。
这个错误跟踪就是在我解压缩的地方,
/*
* 解压GZip
* @param data
* @return
*/
public byte[] unCompress(byte[] data) {
byte[] b = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream(data);
GZIPInputStream gzip = new GZIPInputStream(bis);
byte[] buf = new byte[data.length];
int num = -1;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((num = gzip.read(buf, 0, buf.length)) != -1) {//报错就在这read方法里,没找到正确的结束符
baos.write(buf, 0, num);
}
baos.flush();
b = baos.toByteArray();
baos.close();
gzip.close();
bis.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return b;
}
这地方试了好几种流也没搞定,后来我就以为服务端Socket发送数据时候出了问题,一直测也没出来结果,最后还是有个同事,仔细看了他自己写的东西,经过修改大半天,发现是网络流传过来的时候没读完整导致这问题出现了。
//省略
Socket socket=null;
DataOutputStream dos=null;
DataInputStream dis=null;
try {
//从Map里面获取.
socket=new Socket(peerip,peerport);
socket.setSoTimeout(timeout);
dos = new DataOutputStream(socket.getOutputStream());
dis = new DataInputStream(socket.getInputStream());
dos.write(data);
dos.flush();
byte[] len=new byte[8];
dis.read(len);//数据规则总长度
int length = Integer.parseInt(new String(len).trim());
byte[] bCode=new byte[4];
dis.read(bCode);//数据规则码
String code=new String(bCode);
length = length-8;
byte[] body = new byte[length];
int num = 0;
while(num<length) {//问题就出在这里,原来是写dis.read(body, 0, length);
num += dis.read(body,num,length - num);
}
byte[] bContent = unCompress(body);//解压
return new String(bContent);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//省略
这样的错增长了一次见识,记录下来