Skip to content

Instantly share code, notes, and snippets.

@melin
Created May 21, 2014 10:48
Show Gist options
  • Save melin/5d9067a96785f4f52cd1 to your computer and use it in GitHub Desktop.
Save melin/5d9067a96785f4f52cd1 to your computer and use it in GitHub Desktop.
1、ByteBuf支持同时读写操作,包含writerIndex和readerIndex两个变量,如果readerIndex值超过writerIndex,将会抛出IndexOutOfBoundsException错误。
2、ByteBuf支持head buffer(jvm堆中)和direct buffer,堆外分配buffer成本更高。
3、使用ByteBuffer实例:
ByteBuf heapBuf = ...;
if (heapBuf.hasArray()) { #1
byte[] array = heapBuf.array(); #2
int offset = heapBuf.arrayOffset() + heapBuf.position(); #3
int length = heapBuf.readableBytes(); #4
YourImpl.method(array, offset, length); #5
}
4、随机访问ByteBuffer
ByteBufbuffer = ...;
for (int i = 0; i < buffer.capacity(); i ++) {
byte b = buffer.getByte(i);
System.out.println((char) b);
}
5、顺序访问ByteBuffer(writerIndex和readerIndex)
6、调用discardReadBytes方法,重置writerIndex和readerIndex。使得readerIndex值重新为0.
7、读取字节,readerIndex值将增加
ByteBuf buffer = ...;
while (buffer.readable()) {
System.out.println(buffer.readByte());
}
8、 写入字节,writerIndex值将增加
ByteBuf buffer = ...;
while (buffer.writableBytes() >= 4) { //是否有足够的空间写入
buffer.writeInt(random.nextInt());
}
9、clear()方法把writerIndex和readerIndex方法设置为0,不清清除buffer中数据。
10、bytesBefore()
11、派生的缓冲区:duplicate(), slice(), slice(int, int), readOnly(), or order(ByteOrder)
Charset utf8 = Charset.forName(“UTF-8“);
ByteBuf buf = Unpooled.copiedBuffer(“Netty in Action rocks!“, utf8);
ByteBuf sliced = buf.slice(0, 14); //copy
System.out.println(sliced.toString(utf8);
buf.setByte(0, (byte) ’J’);
assert buf.get(0) == sliced.get(0);
12、get和set开头的方法,不影响writerIndex和readerIndex值。
13、类型占用字节长度
boolean = 1
byte = 1
int = 4
long = 8
short = 2
14、其它主要方法
isReadable:至少有一个字节可读返回true
isWritable:至少能写入一个字节返回true
readableBytes:返回能够读取的字节数
writablesBytes:返回能够写入的字节数
15、ByteBufAllocator 通过Channel和ChannelHandlerContext获取
Channel channel = ...;
ByteBufAllocator allocator = channel.alloc();
....
ChannelHandlerContext ctx = ...;
ByteBufAllocator allocator2 = ctx.alloc();
16、ByteBufUtil.hexdump() 打印出ByteBuffer十六进制内容。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment