欢迎来到天天文库
浏览记录
ID:8846726
大小:31.50 KB
页数:2页
时间:2018-04-09
《用字节流进行socket通信》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库。
1、由于输入流无法准确获取信息实际长度,所以在发送信息的时候必须告诉另一方信息的长度是多少,所以我们必须把长度也封装成字节数组,下面这个函数就起到了此功能;/***将一个int型数据转换成字节数组*@paramintegerint型数据*@paramlen此数据所占字节数*@return转换后的字节数组*/publicstaticbyte[]intToByte(intinteger,intlen){if(integer<0){thrownewIllegalArgumentException("Cannotcastnegativetobytes:"+integer);}B
2、yteArrayOutputStreambo=newByteArrayOutputStream();for(inti=0;i>8;}//返回此字节数组returnbo.toByteArray();}在另一端接收时,首先必须知道信息的长度才能读,所以需要先读取长度,下面此方法即从输入流中读取指定长度的字节数组一般读取长度时为readBytes(in,4);即从输入流中读取前4个字节这4个字节就是信息的长度length信息(int为4个字节)。
3、知道长度后在调用readBytes(in,length);这样就可以实现将长度信息和内容信息分别读取的效果;/***读取输入流中指定字节的长度*@paramin输入流*@paramlength指定长度*@return指定长度的字节数组*/publicstaticbyte[]readBytes(InputStreamin,longlength){ByteArrayOutputStreambo=newByteArrayOutputStream();byte[]buffer=newbyte[1024];intread=0;intcur=0;;while(read4、th){try{cur=in.read(buffer,0,(int)Math.min(1024,length-read));}catch(IOExceptione){ExceptionUtil.throwActualException(e);}if(cur<0){break;}read+=cur;bo.write(buffer,0,cur);}returnbo.toByteArray();}}读出长度后(为一个长度为4的字节数组)需要将其转换为数字,会用到下面此方法。/***将一个byte数组转换为int型数据*@parambytesbyte数组*@returnin5、t数据*/publicstaticintbytesToInteger(byte[]bytes){intinteger=0;intlen=bytes.length;for(inti=0;i6、bytes[i];temp=temp<<8*i;integer=integer7、temp;}returninteger;}
4、th){try{cur=in.read(buffer,0,(int)Math.min(1024,length-read));}catch(IOExceptione){ExceptionUtil.throwActualException(e);}if(cur<0){break;}read+=cur;bo.write(buffer,0,cur);}returnbo.toByteArray();}}读出长度后(为一个长度为4的字节数组)需要将其转换为数字,会用到下面此方法。/***将一个byte数组转换为int型数据*@parambytesbyte数组*@returnin
5、t数据*/publicstaticintbytesToInteger(byte[]bytes){intinteger=0;intlen=bytes.length;for(inti=0;i6、bytes[i];temp=temp<<8*i;integer=integer7、temp;}returninteger;}
6、bytes[i];temp=temp<<8*i;integer=integer
7、temp;}returninteger;}
此文档下载收益归作者所有