模拟黏包半包

    public static void main(String[] args) {
        ByteBuffer source = ByteBuffer.allocate(32);
        source.put("Hello,world\nI am zhangSan\nHo".getBytes());
        split(source);
        source.put("w are you?\n".getBytes());
        split(source);
    }

    private static void split(ByteBuffer source) {
        source.flip();
        for (int i = 0; i < source.limit(); i++) {
            // 找到一条信息
            if (source.get(i) == '\n') {
                // 新建一个buffer
                int length = i + 1 - source.position();
                ByteBuffer target = ByteBuffer.allocate(length);
                // 从source写入target
                for (int j = 0; j < length; j++) {
                    target.put(source.get());
                }
                target.flip();
                log.info(StandardCharsets.UTF_8.decode(target).toString());
            }
        }
        source.compact();
    }

运行结果:
WX20220424-004107@2x