Anatomy for Netty 3.2
Today, Netty's encoder and decoder (coder its essence or handler) are used to analyze the Netty provided by coder to select or implement my own coder.
1. Why do encoder and decoder?
As we all know, the network transmits the byte stream, and our object-oriented programming operation is object or basic data type, so we need to convert the object or the basic type to byte before transmitting.
The byte is then converted to an object or base type. At the same time, for Netty is based on the NIO framework, and NIO relative to Oio is a significant feature is that the transmission is based on buffering (buffer), so before transmission in Netty: Object-->channelbuffer, after receiving: channelbuffer-- > Objects. All coder implementations of Netty are based on this guideline.
2. Coder Package Structure:
It can be seen that Netty has implemented many different types of coder to support different types or protocols.
3. Analyze the Objectencoder and Objectdecoder in the Org.jboss.netty.handler.codec.serialization package:
You can see the encoder () method of the Objectencoder class:
@Override79protectedObject Encode (Channelhandlercontext CTX, channel Channel, Object msg)throwsException {channelbufferoutputstream bout =81NewChannelbufferoutputstream (Dynamicbuffer (Estimatedlength, Ctx.getchannel (). GetConfig (). GetBufferFac Tory ())); Bout.write (Length_placeholder); ObjectOutputStream oout =NewCompactobjectoutputstream (bout); Oout.writeobject (msg); Oout.flush (); Oout.close (); 88 89 Channelbuffer encoded = Bout.buffer (); Encoded.setint (0, Encoded.writerindex ()-4); 91returnENCODED;92}
follow-up to see the Compactobjectoutputstram Class WriteObject () method, in fact, is the use of Java itself provides a serialization mechanism ObjectOutputStream class Writerobject () method.
The decode () method of the Objectdecoder class is also based on the Java object serialization principle, slightly.