djxak

ByteBuffer to send bytes in chunks of 8

Dec 8th, 2021
659
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package com.example;
  2.  
  3. import java.nio.ByteBuffer;
  4. import java.util.Arrays;
  5.  
  6. public class ByteBufferTests {
  7.  
  8.     private final ByteBuffer buf = ByteBuffer.allocate(8);
  9.  
  10.     public static void main(String[] args) {
  11.         ByteBufferTests bbt = new ByteBufferTests();
  12.         bbt.onReceive(new byte[]{1, 2, 3});
  13.         bbt.onReceive(new byte[]{4, 5});
  14.         bbt.onReceive(new byte[]{6, 7, 8});
  15.         bbt.onReceive(new byte[]{9, 10, 11, 12, 13, 14, 15, 16});
  16.         bbt.onReceive(new byte[]{17, 18, 19, 20, 21, 22, 23, 24, 25, 26});
  17.  
  18.         bbt.buf.flip();
  19.         byte[] bytes = new byte[bbt.buf.remaining()];
  20.         bbt.buf.get(bytes);
  21.         System.out.println("Remaining bytes: " + Arrays.toString(bytes));
  22.     }
  23.  
  24.     public void onReceive(byte[] bytes) {
  25.         ByteBuffer rBuf = ByteBuffer.wrap(bytes);
  26.  
  27.         while (true) {
  28.             int maxBytesToRead = Math.min(buf.remaining(), rBuf.remaining());
  29.             for (int i = 0; i < maxBytesToRead; i++) {
  30.                 buf.put(rBuf.get());
  31.             }
  32.             if (buf.remaining() == 0) {
  33.                 buf.flip();
  34.                 byte[] nextBytes = new byte[buf.remaining()];
  35.                 buf.get(nextBytes);
  36.                 buf.clear();
  37.                 System.out.println("onNext(" + Arrays.toString(nextBytes) + ")");
  38.             } else {
  39.                 break;
  40.             }
  41.         }
  42.     }
  43.  
  44. }
  45.  
RAW Paste Data