Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a ByteBuf in Netty 4.0

Tags:

java

nio

netty

Two simple questions, which I am not able to solve by reading the documentation:

  1. I have a byte[]
    • How can i convert it to a ByteBuf?
  2. I have a NIO ByteBuffer
    • How can i convert it to a ByteBuf?
like image 433
Dennis Avatar asked Feb 26 '13 11:02

Dennis


People also ask

What is ByteBuf in Netty?

Sequential Access Indexing ByteBuf provides two pointer variables to support sequential read and write operations - readerIndex for a read operation and writerIndex for a write operation respectively.

What is ByteBuf in java?

ByteBuffer is among several buffers provided by Java NIO. Its just a container or holding tank to read data from or write data to. Above behavior is achieved by allocating a direct buffer using allocateDirect() API on Buffer. Java Documentation of Byte Buffer has useful information.

What is Netty buffer?

buffer Description. Abstraction of a byte buffer - the fundamental data structure to represent a low-level binary and text message. Netty uses its own buffer API instead of NIO ByteBuffer to represent a sequence of bytes. This approach has significant advantage over using ByteBuffer .


1 Answers

The documentation seems pretty clear to me:

Creation of a buffer

It is recommended to create a new buffer using the helper methods in Unpooled rather than calling an individual implementation's constructor.

Then in Unpooled, you've got options of wrapping or copying. For example:

  • Unpooled.copiedBuffer(ByteBuffer)
  • Unpooled.copiedBuffer(byte[])
  • Unpooled.wrappedBuffer(ByteBuffer)
  • Unpooled.wrappedBuffer(byte[])

Choose whichever method is appropriate based on whether you want changes made in the returned ByteBuf to be passed through to the original byte array/buffer.

like image 160
Jon Skeet Avatar answered Oct 14 '22 00:10

Jon Skeet