当前位置: 代码迷 >> 综合 >> Java中对于字节流的读取方式
  详细解决方案

Java中对于字节流的读取方式

热度:49   发布时间:2024-02-01 16:52:40.0

大家好:

今天我想介绍一下socket中字节流的读取方式,避免在socket读取过程中发生的断包问题。

1.设计字节发送的方式

在字节流的读写过程中,需要先发送一个代表发送内容长度的字节,然后再发送内容,在接收端先接受发送端发送的内容长度,再根据长度来读取相应的内容。

2.构建字节流的读写类

 


 
  1. BufferedInputStream in = new BufferedInputStream(socket.getInputStream());

  2. BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());

 3.发送端的发送方式

 

 


 
  1. out.write(NumberUtil.intToByte(data.length));// NumberUtil类是把int和字节转换的类,在附件中附送

  2. out.write(data);

  3. out.flush();

 4.接收端的接收方式

 

 


 
  1. protected byte[] read() throws IOException {

  2. byte[] buf = null;

  3. // 读取长度

  4. int contentLength = readInt();

  5.  
  6. // 如果消息的长度不够

  7. if (contentLength > in.available()) {

  8. buf = BytesUtil.readBytes(in, contentLength);//BytesUtil类为读取指定长度字节的一个共通类,在附件中附送,也就是说当前缓冲流的可读字节长度<真实字节长度,那么我们需要一直读,直到读取了我们需要的长度

  9. } else {

  10. buf = new byte[contentLength];

  11. in.read(buf, 0, contentLength);

  12. }

  13.  
  14. return buf;

  15. }

  16.  
  17. private int readInt() throws IOException {

  18. // 四个字节大小

  19. byte[] tmpByte = new byte[4];

  20. // 读取四个字节判断消息长度

  21. in.read(tmpByte, 0, 4);

  22. // 将byte转为int

  23. return NumberUtil.byteToInt(tmpByte);

  24. }

 5.介绍readBytes方法


 
  1. /**

  2. *    读取输入流中指定字节的长度   

  3. *

  4. * @param in     输入流     

  5. * @param length 指定长度     

  6. * @return       指定长度的字节数组 

  7. */

  8. public static byte[] readBytes(InputStream in, long length) throws IOException {

  9. ByteArrayOutputStream bo = new ByteArrayOutputStream();// 建立字节流

  10. byte[] buffer = new byte[1024];//1024长度

  11. int read = 0;

  12. while (read < length) {// 循环将需要读取内容写入到bo中

  13. int cur = in.read(buffer, 0, (int) Math.min(1024, length - read));

  14. if (cur < 0) {//直到读到的返回标记为-1,表示读到流的结尾

  15. break;

  16. }

  17. read += cur;//每次读取的长度累加

  18. bo.write(buffer, 0, cur);

  19. }

  20. return bo.toByteArray();//返回内容

  21. }

 总结:基于TCP/IP的传输方式中,TCP是不会丢包的,如果在你的程序中发生了字节的丢失,请检查你的socket输入字节流的读取方式,一定要注意以上代码中的红色标出的内容。

 

感谢你的阅读,对自己负责、对父母感恩!