Packet sticking during Mina socket communication

Source: Internet
Author: User

During socket communication, we often encounter packet sticking problems! Nima has a high probability of frequent data increases.

Mina has considered this problem. cumulativeprotocoldecoder is answer!

Cumulativeprotocoldecoder class, a cumulative protocol decoder, that is, as long as there is data sent, this class will read the data and then accumulate it into the internal iobuffer, however, the specific package (decoding the data accumulated into the buffer into a Java object) is completed by the dodecode () method of the subclass. In fact, cumulativeprotocoldecoder is in decode () repeatedly call the dodecode () method implemented by the subclass.

The specific execution process is as follows:

A. when your dodecode () method returns true, the decode () method of cumulativeprotocoldecoder first checks whether you have read data from the internal iobuffer in the dodecode () method. If not, CE); buffer. putstring (smscontent, CE); buffer. flip (); will throw an invalid status exception, that is, your dodecode () if the method returns true, it indicates that you have consumed the data (equivalent to reading a complete message in the chat room). Further, that is, you must have consumed the data in the internal iobuffer buffer (even if one byte of data is consumed ). If the verification succeeds, cumulativeprotocoldecoder checks whether there is any data in the buffer zone that has not been read. If yes, it continues to call the dodecode () method. If no, it stops calling the dodecode () method, until new data is buffered.

B. when your dodecode () method returns false, cumulativeprotocoldecoder stops calling the dodecode () method. However, if the data has not been read, the iobuffer buffer with the remaining data is saved to the iosession so that the next time the data arrives, it can be extracted and merged from the iosession. If all data is read, The iobuffer is cleared. In short, if you think the read data is enough to be decoded, true is returned; otherwise, false is returned. The most important task of this cumulativeprotocoldecoder is to help you complete the data accumulation, because this work is very cumbersome.

Cumulativeprotocoldecoder:

 
Public voidDecode(Iosession session, iobuffer in, protocoldecoderoutput out) throws exception
Cumulates contentInInto internal buffer and forwards decoding requestDodecode (iosession, iobuffer, protocoldecoderoutput).Dodecode ()Is invoked repeatedly until it returnsFalseAnd the cumulative buffer is compacted After decoding ends.
Throws:
Illegalstateexception-If your Dodecode ()Returned TrueNot consuming the cumulative buffer.
Exception-If the read data violated protocol specification
 
Note: The decode function adds the content in the iobuffer in object to the internal buffer and calls the dodecode method ., If the dodecode method returns false and the data in the buffer accumulation is available again, the dodecode method is called again until the dodecode method returns true;

Protected Abstract BooleanDodecode(Iosession session, iobuffer in, protocoldecoderoutput out) throws exception
Implement this method to consume the specified cumulative buffer and decode its content into message (s ).
Parameters:
In-The cumulative Buffer
Returns:
TrueIf and only if there's more to decode in the buffer and you want to have DodecodeMethod invoked again. Return FalseIf remaining data is not enough to decode, then this method will be invoked again when more data is cumulated.
Throws:
Exception-If cannot decode In.
Note: If the length of data in the cumulative buffer exceeds the length required by the parsing protocol, true is returned. If the returned result of this method is true, this method is called again. If the data in the accumulated buffer is not enough to parse the required length, false is returned until the data in the accumulated buffer is available again.

Example:

Public class asresponsedecoder extends cumulativeprotocoldecoder {Private Static logger log = loggerfactory. getlogger (asresponsedecoder. class); private final charset; Public asresponsedecoder (charset) {This. charset = charset;}/*** the return value of this method is important: * 1. When the content is good, false is returned, inform the parent class to receive the next batch of content * 2. if the content is insufficient, the next batch of content needs to be sent. At this time, false is returned, so that the parent class cumulativeprotocoldecoder * will put the content into iosession, wait for the next data to be assembled and then handed over to the dodecod class. E * 3. If the content is too large, true is returned because the data in this batch needs to be read, the parent class pushes the remaining data to the dodecode */Public Boolean dodecode (iosession session, iobuffer in, protocoldecoderoutput out) throws exception {charsetdecoder Cd = charset. newdecoder (); If (in. remaining ()> 0) {// when there is data, read 4 bytes to determine the message Length byte [] sizebytes = new byte [4]; In. mark (); // mark the current position for reset in. get (sizebytes); // read the first 4 bytes. // numberutil is a tool class written by yourself to convert int to byte []. Int size = numberutil. bytear Raytoint (sizebytes); // returns true if (size> in. remaining () {// if the message content is insufficient, reset, equivalent to not reading size in. reset (); Return false; // receives new data to splice it into complete data} else {byte [] bytes = new byte [size]; In. get (bytes, 0, size); string xmlstr = new string (bytes, "UTF-8"); system. out. println ("------------" + xmlstr); If (null! = Xmlstr & xmlstr. Length ()> 0) {asresponse rescmd = new asresponse (); asxmlpacker. parse (rescmd, xmlstr); If (rescmd! = NULL) {out. write (rescmd) ;}} if (in. remaining ()> 0) {// If the packet is attached after the content is read, the parent class will be re-resolved and return true; }}} return false; // The processing is successful, and the parent class is allowed to receive the next package }}

Iobuffer functions:

Capacity: The size of the On-premises memory. Once set, it cannot be changed. Note: this refers to native NiO.

Limit: supports reading/writing statistics. When writing a buffer, limit indicates how much space can be written. When writing from the buffer, limit indicates the number of records that can be written.

Position: The next location to be read or written.

MARK: Mark bit. You can remember a position to facilitate subsequent operations.

The following operations are commonly used for bytebuffer:

Flip (): converts the read/write mode.

Rewind (): resets position to 0, which is generally used for repeated read.

Clear (): clears the buffer and prepares to be written again (position is changed to 0, and limit is changed to capacity ).

Compact (): Copy unread data to the buffer header.

Mark (), reset (): Mark can mark a position, and reset can be reset to this position.

Get (), getshort (), and other get operations: Get the content in bytebuffer. Of course, the get content starts from position, so always pay attention to position. Position Changes after each get operation. The change in position is based on your get type. If it is short, it is two bytes. If it is int, it is increased by four bytes, that is, 32.

Put (), putshort (), and other put operations: add content to bytebuffer. Put content starts from position. Position Changes after each put operation.

Of course, there are also common methods such as allocate and hasremaining. However, these methods generally do not have errors, and they are not very relevant to the use of four attributes. Note: buffers are NOT thread-safe. if you want to access a given buffer concurrently from multiple threads, you will need to do your own synchronization prior to accessing the buffer. what is the use of buffer or bytebuffer? That's too much. It can be used as long as it involves transmission and communication. Of course, you can also use its original meaning as a buffer.

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.