Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example;
- import java.nio.ByteBuffer;
- import java.util.Arrays;
- public class ByteBufferTests {
- private ByteBuffer buf = ByteBuffer.allocate(8);
- public static void main(String[] args) {
- ByteBufferTests bbt = new ByteBufferTests();
- bbt.onReceive(new byte[]{1, 2, 3});
- bbt.onReceive(new byte[]{4, 5});
- bbt.onReceive(new byte[]{6, 7, 8});
- bbt.onReceive(new byte[]{9, 10, 11, 12, 13, 14, 15, 16});
- bbt.onReceive(new byte[]{17, 18, 19, 20, 21, 22, 23, 24, 25, 26});
- bbt.buf.flip();
- byte[] bytes = new byte[bbt.buf.remaining()];
- bbt.buf.get(bytes);
- System.out.println("Remaining bytes: " + Arrays.toString(bytes));
- }
- public void onReceive(byte[] bytes) {
- ByteBuffer rBuf = ByteBuffer.wrap(bytes);
- while (true) {
- int maxBytesToRead = Math.min(buf.remaining(), rBuf.remaining());
- for (int i = 0; i < maxBytesToRead; i++) {
- buf.put(rBuf.get());
- }
- if (buf.remaining() == 0) {
- byte[] nextBytes = buf.array();
- System.out.println("onNext(" + Arrays.toString(nextBytes) + ")");
- buf = ByteBuffer.allocate(8);
- } else {
- break;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement