ByteArrayInputStream和ByteArrayOutputStream

本文介绍如何利用ByteArrayInputStream和ByteArrayOutputStream优化客户端与服务器之间的数据交互过程,通过一次性读取完整数据包并本地解析,减少网络资源消耗。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ByteArrayInputStream的精髓是将一个字节数组包装到流中
有这样一个场景:
客户端和服务器端交互,当连接建立之后,如果只是根据协议用DataInputStream的readInt() 或者readByte() 等固定方法一个一个的读,那是相当消耗资源的,如果一次将所需要的数据读取完毕,然后剩下的就是本地解析,那就省了不少交互资源

 

int packetlen = din.readInt();
int len = packetlen-4;
byte[] b = new byte[len];
din.readFully(b);

 

这段代码一次读够了客户端过来的数据

然后

ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(b);
DataInputStream dataInputStream = new DataInputStream(byteArrayInputStream);
//此时的输入流已经是本地的输入流了,在本地你可以随心所欲
dataInputStream.readByte() 
dataInputStream.readInt() 
.....

 

 

ByteArrayOutputStream创建一个新的字节数组输出流
场景如下:服务器端处理完毕需要往客户端返回数据,如果使用DataOutputStream的writeInt(int v)或者writeByte(int v)等方法一个一个的写,那么和读取的场景性质就一样了:交互资源是相当消耗的;因此如果现在本地把数据组织完毕之后,能一次传送,就好了。

声明字节数组输出流

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(29);

 

对字节数组输出流进行包装,这样写入的时候,数据真正进入的还是ByteArrayOutputStream

DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);

 

往流当中写入数据

dataOutputStream.writeInt(29);//packetlen
dataOutputStream.writeInt(JVConstant.SGIP_BIND_RESP);//command
dataOutputStream.write(sequence);//sequence-number
dataOutputStream.writeByte(0);//Result
byte[] reserve = new byte[8];
dataOutputStream.write(reserve);//Reserve
dataOutputStream.flush();

 

从字节数组输出流当中将数据读取出来

byte[] result = byteArrayOutputStream.toByteArray();

 

关闭流

byteArrayOutputStream.close();
dataOutputStream.close();

 

返回字节数据

return result;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值