Unpooled 工具类的使用

您所在的位置:网站首页 charsetutil Unpooled 工具类的使用

Unpooled 工具类的使用

2023-07-07 08:25| 来源: 网络整理| 查看: 265

Netty 提供一个专门用来操作缓冲区(即Netty的数据容器)的工具类:io.netty.buffer.Unpooled

之前简单用过,如下:

/** * 通道就绪事件 * * @param ctx * @throws Exception */ @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { log.info("ClientHandler ctx: " + ctx); ctx.writeAndFlush(Unpooled.copiedBuffer("hello, 服务器!", CharsetUtil.UTF_8)); }

查看AbstractByteBuf 有三个属性,

readerIndex 下次读取的下标

writerIndex 下次写入时的下标

maxCapacity 容量

通过 readerindex 和 writerIndex 和 capacity, 将buffer分成三个区域:

0---readerindex 已经读取的区域;readerindex---writerIndex , 可读的区域;writerIndex -- capacity, 可写的区域。

1. 测试一

package netty; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; public class NettyByteBuf01 { public static void main(String[] args) { //创建一个ByteBuf //说明 //1. 创建对象,该对象包含一个数组arr,是一个byte[10] //2. 在netty 的buffer中,不需要使用flip 进行反转 // 底层维护了 readerindex 和 writerIndex //3. 通过 readerindex 和 writerIndex 和 capacity, 将buffer分成三个区域 // 0---readerindex 已经读取的区域 // readerindex---writerIndex , 可读的区域 // writerIndex -- capacity, 可写的区域 ByteBuf buffer = Unpooled.buffer(10); for (int i = 0; i < 10; i++) { buffer.writeByte(i); } System.out.println("capacity=" + buffer.capacity());//10 //输出 // for(int i = 0; i


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3