1

I am designing a binary protocol for client/server communication using Netty and the number of bytes sent is not fixed amount and can be arbitrary size.

The client is sending something like this:

first 4 bytes to represent an id number the remaining bytes is a String

In the example I have seen, the message has been a fixed size but the String content could be any size and need to ensure it is not fragmented when received by the server. How would I achieve this in Netty?

Thanks in advance.

algolicious
  • 1,182
  • 2
  • 10
  • 14

2 Answers2

4

How are you determining the end of message? A zero? I would check out the Netty replaying decoder:

http://docs.jboss.org/netty/3.2/api/org/jboss/netty/handler/codec/replay/ReplayingDecoder.html

It makes things easy for you. Just keep reading until you find a zero. If you run out of bytes before you reach the zero an exception will be thrown to exit the decode method. When more bytes are available, the decode method will be called again with the existing bytes and the new bytes combined in one ChannelBuffer.

This cycle can repeat until you have the whole message in the ChannelBuffer...which then you can pass up to the next layer for processing.

If it was possible to change your protocol I would add a length as being able to read to length is far more efficient than checking every byte for a zero.

Gareth
  • 936
  • 6
  • 14
  • 1
    Hi Gareth, thanks for the answer - very appreciated. I am currently not using anything to determine the end of a message. Once I retrieve the id by invoking buffer.readLong(), I then invoke buffer.toString(String charsetName) - which is not ideal. When you refer to sending the size of the payload, are you suggesting to add it to the beginning and wait until the length is received, and use that arbitrary number to determine to wait for more bytes on the server? – algolicious Jan 19 '12 at 10:12
  • Yes. Once you have a length you can instead use the LengthFieldBasedFrameDecoder (if your messages are likely to be very large though it is probably better to write your own based on SimpleChannelUpstreamHandler so that the buffer is only allocated once). – Gareth Jan 19 '12 at 16:27
2

Or if its line based you could just use the DelimiterBasedFrameDecoder for the job.

See: http://netty.io/docs/stable/api/org/jboss/netty/handler/codec/frame/DelimiterBasedFrameDecoder.html

Norman Maurer
  • 23,104
  • 2
  • 33
  • 31