ByteBuf详解

在Netty中,还有另外一个比较常见的对象ByteBuf,它其实等同于Java Nio中的ByteBuffer,但是ByteBuf对Nio中的ByteBuffer的功能做了很多增强,下面介绍一下ByteBuf。

字节写入ByteBuf

        //分配非池化,10个字节的ByteBuf
        ByteBuf buf = Unpooled.buffer(10);
        byte[] bytes3 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
        buf.writeBytes(bytes3);
        System.out.println("ByteBuf参数:" + buf.toString());
        System.out.println("ByteBuf中的内容:" + Arrays.toString(buf.array()) + "\n");

ByteBuf转字节

        ByteBuf buf = (ByteBuf)msg;
        byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);
        System.out.println(BinaryToHexString(bytes));
//        String body = new String(bytes,"UTF-8");

​ 下面这段代码演示了ByteBuf的创建以及内容的打印,这里显示出了和普通ByteBuffer最大的区别之一,就是ByteBuf可以自动扩容,默认长度是256,如果内容长度超过阈值时,会自动触发扩容

public class ByteBufExample {

    public static void main(String[] args) {
        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(); //可自动扩容
        log(buffer);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 128; i++) {
            sb.append(" - " + i);
        }
        buffer.writeBytes(sb.toString().getBytes());
        log(buffer);
    }

    private static void log(ByteBuf buf) {

        StringBuilder builder = new StringBuilder()
            .append(" read index:").append(buf.readerIndex())//获取读索引
            .append(" write index:").append(buf.writerIndex()) //获取写索引
            .append(" capacity:").append(buf.capacity())//获取容量
            .append(StringUtil.NEWLINE);
        //把ByteBuf中的内容,dump到StringBuilder中
        ByteBufUtil.appendPrettyHexDump(builder, buf);
        System.out.println(builder.toString());
    }
}

参考:https://www.cnblogs.com/snail-gao/p/15595747.html

posted @ 2022-10-26 10:08  离人怎挽_wdj  阅读(612)  评论(0编辑  收藏  举报