netty--advanced built-in decoder, encoder, BYTEBUF

Source: Internet
Author: User
Tags base64

Netty communication needs to encode and decode the data, so we need to use the Netty Encoder, decoder

decoder provided by Netty

  Delimiterbasedframedecoder Resolving TCP's sticky-packet decoder
  Stringdecoder              Message turns into a string decoder
  Linebasedframedecoder      Auto-complete Identifier separator decoder
  Fixedlengthframedecoder    Fixed length decoder , binary
  base64decoder base64       Decoder

Encoders provided by the Netty
Base64 Encoder
  The message is converted to a string encoder
  Auto-complete Identifier separator encoder

  messagetomessageencoder encoding a Message object according to the message object


For Netty data transfer is BYTEBUF, we generally rewrite the above decoder, encoder to implement their own logic


1. Delimiterbasedframedecoder Solution for TCP sticky packet decoder
Iodecoder  
/*** decode * delimiterbasedframedecoder prevent the bag from dipping *@authorFLM * October 30, 2017*/ Public classIodecoderextendsDelimiterbasedframedecoder { Public Static Finalattributekey<devicesession> KEY = attributekey.valueof ("IO");//Save    Private Static FinalLogger log = Logger.getlogger (Iodecoder.class); //Prevent packet Separators    Private StaticBytebuf delimiter = Unpooled.copiedbuffer ("\ n". GetBytes ()); //Dip-bag divider \ n  Private Static intMaxframelength = 1024 * 6; //Data size  PublicIodecoder () {Super (maxframelength, delimiter); }    /*** Re-customize decoding*/@OverrideprotectedObject Decode (Channelhandlercontext ctx, bytebuf buffer)throwsException {//decoding the data buffer        return Super. Decode (ctx, buffer); }}

2, Messagetomessageencoder Encoder

/*** Instruction Code * messagetomessageencoder<pushentity> * Encode Pushenty As String *@authorFLM * November 3, 2017*/ Public classIoencoderextendsMessagetomessageencoder<pushentity> {    Private Static FinalLogger LOG = Logger.getlogger (ioencoder.class);  PublicIoencoder () {Super(); }            /*** Rewrite the code*/@Overrideprotected voidEncode (Channelhandlercontext ctx, pushentity msg, list<object> out)throwsException {Try{pushentity Push=(pushentity) msg; }                //Send As a stringOut.add (bytebufutil.encodestring (Ctx.alloc (), Charbuffer.wrap (Msg.tostring ()), Charset.defaultcharset ()); } Catch(Exception e) {e.printstacktrace (); }    }}    

3, Fixedlengthframedecoder fixed length decoder, binary

/*** Function Description: Protocol message Decoder
* Convert Btyebuf to rootmessage object **/ Public classGt06msgdecoderextendslengthfieldbasedframedecoder{ PublicGt06msgdecoder () {Super(65540, 2, 1, 2, 0); //Inheritance }

  /*
* Rewrite decoding
* /@Override PublicObject Decode (Channelhandlercontext ctx, bytebuf in)throwsException {bytebuf frame= (BYTEBUF)Super. Decode (CTX, in);
    //Read BYTEBUF is read according to the number of bits Try { if(frame = =NULL) { return NULL; } intFramelen =frame.readablebytes (); //starting bit byte[] Header =New byte[Gt06constant.start_delimiter_len]; Frame.readbytes (header); //whether it is an expansion pack beginning with 0x79 0x79 BooleanExtpacket =false; if(Arrays.equals (Gt06constant.packet_start_ext, header)) {Extpacket=true; } intContentlen =Messageutils.getcontentlen (Framelen, Extpacket); //Skip Package Lengthframe.skipbytes (Messageutils.getpacketsizelen (Extpacket)); //Message Content byte[] Msgcontent =New byte[Contentlen]; //Message serial number byte[] sequence =New byte[Gt06constant.message_serial_len]; //CRC Check Code byte[] CRC =New byte[Gt06constant.crc_itu_len]; //terminating character byte[] Enddelimiter =New byte[Gt06constant.end_delimiter_len];
     return NewRootmessage (action, sequence, msgcontent); } finally { if(Frame! =NULL) {frame.release (); } } }

Other encoders, decoders are similar, do not understand the source code can see




In fact, decoding, encoding, the most important thing is to read the BTYEBUF
Btyebuf read operations mainly provide the following functions:

    • ReadByte: Take 1 bytes of content;
    • Skipbytes: Skip Content
    • Readunsignedbyte: Take 1 bytes of content, return ( (short) (readByte() & 0xFF) ); (Can you convert negative numbers to unsigned?) )
    • Readshort: Takes 2 bytes of content, returns the converted short type;
    • Readunsignedshort: Take 2 bytes of content, return readShort() & 0xFFFF ;
    • Readmedium: Takes 3 bytes of content, returns the converted int type;
    • Readunsignedmedium: Takes 3 bytes of content, returns the converted int type;
    • ReadInt: Take 4 bytes of content;
    • Readunsignedint: Take 4 bytes of content, return readInt() & 0xFFFFFFFFL ;
    • Readlong: Take 8 bytes of content;
    • ReadChar: Take 1 bytes of content;
    • Readfloat: Take 4 bytes of int content, convert to float type;
    • Readdouble: Takes 8 bytes of long content, converted to double type;
    • Readbytes: Takes the content of the specified length, returns the ByteBuf type;
    • Readslice: Takes the content of the specified length, returns the ByteBuf type;
    • Readbytes: Takes the specified length of content to the target container.
Write operations

The function provided by the write operation is to write the byte content to bytebuf, no longer one by one to repeat. The main difference is that a byte array is converted to a relative length based on the type before writing.

The main functions are: Writeboolean, WriteByte, Writeshort, Writemedium, Writeint, Writelong, Writechar, Writefloat, WriteDouble, Writebytes, Writezero.

Boundary value Security

No matter read or write, there will be a case where the BYTEBUF data is empty or full, and as a data container, there must be a boundary value check to ensure read and write security.

netty--advanced built-in decoder, encoder, BYTEBUF

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.