一个Socket数据流的问题

今天遇到个错误是关于GZIPInPutStream压缩流的问题。
一直会爆错: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();
}
//省略


这样的错增长了一次见识,记录下来
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值