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.
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.