简体   繁体   中英

Netty ByteBuf First Time Implementation

My Plan is to have a message protocol as outlined below:

  • MessageLength : integer with total message length
  • MessageID : integer with auto incrementing identifier
  • MessageType : integer ( enum ) with the type of message
  • Payload : byte[] with the Payload of the message (Serialised POJO)

At the moment I just am looking at making sure I create the ByteBuf in the correct and optimal way. At this stage I have the following:

io.netty.buffer.ByteBuf buf = Unpooled.buffer();

// Test Data Class
TestData test = new TestData("FirstName", "LastName", 40);

// Convert to Bytes is method to return the Byte Array (Serialised POJO)
byte[] payload = convertToBytes(test);

// Write 1 simulating MessageID 1
buf.writeInt(1);

// Write 2 simulating MessageType of 2
buf.writeInt(2);

// Write The Payload data<BR>
buf.writeBytes(payload);

The goal would be to them pass on to a LengthFieldPrepender and up the pipeline.

Is this the right way to create the ByteBuf ? Or is there a better way?

You should use the allocator to create the ByteBuf if possible as this may give you a pooled ByteBuf (depending on the configuration).

Something like:

Channel channel = ...
channel.alloc().buffer(expectedSize)

Also note that I passed in the expected size of the ByteBuf as this will ensure we not need to expand it later on when you fill it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM