package cn.bunny.file_dir;

import java.nio.ByteBuffer;

public class Demo7 {

    public static void main(String[] args) {
        // 黏包 和 半包
        // 黏包：很多字符串连在一起
        // 半包：有部分没有发送完成
        ByteBuffer buffer = ByteBuffer.allocate(32);
        buffer.put("Hello World!\nI'm running\nHo".getBytes());
        split(buffer);
        buffer.put("w are you!".getBytes());
        // split(buffer);
    }

    private static void split(ByteBuffer buffer) {
        buffer.flip();
        for (int i = 0; i < buffer.limit(); i++) {
            if (buffer.get(i) == '\n') {
                int len = i + 1 - buffer.position();
                ByteBuffer target = ByteBuffer.allocate(len);
                for (int j = 0; j < len; j++) {
                    // byte b = buffer.get();
                    target.put(buffer.get());
                }
            }
        }
    }
}
