This problem is more common, in high-concurrency large data transfer when the packet reception will be chaotic
In the Org.jboss.netty.handler.codec.frame package, there is a Lengthfieldbasedframedecoder class to parse a package with a length attribute, as long as we add the total length of the packet to the transport protocol (there may be a better way)
Specific methods:
1. You can add 4 bytes to the packet before the packet to indicate the total length of the package, for example:
/**
* Transfer Protocol
* |------------------------------------------
* | Total length 4byte |pkey length 4byte |
* |------------------------------------------
* | Value 4byte|name 4byte|zip 1 |
* |------------------------------------------
* |skey value 8byte (long-time, fixed) |
* |------------------------------------------------
* | Package Contents |
* |
* |------------------------------------------------
Before transmitting data through Netty, perform
2. In the accepted Channelpipeline, add decoder, before handler, for example:
[Java]View Plaincopy
- Bootstrap.setpipelinefactory (new Channelpipelinefactory () {
- Public channelpipeline Getpipeline () throws Exception {
- Channelpipeline pipeline = new Defaultchannelpipeline ();
- Pipeline.addfirst ("Decoder", new Lengthfieldbasedframedecoder (100000000,0,4,0,4));
- Pipeline.addlast ("Handler", new XXX (config));
- return pipeline;
- }
- });
Using Lengthfieldbasedframedecoder as the decoder implementation, the Lengthfieldbasedframedecoder constructor, the first parameter is the maximum length of information, exceeding this length return exception, The second parameter is the start (offset) bit of the length attribute, the length of our protocol is 0 to 3rd bytes, so here we write 0, the third parameter is the length of the length property, we are 4 bytes, so write 4, the fourth parameter is the length adjustment value, when the total length is defined as containing the header length, the length of the correction information The fifth parameter is the number of skipped bytes, and we skip the first 4 bytes as needed so that the receiving side directly accepts content that does not contain the length attribute.
At this point, the receiving end will not call handler to continue processing the information until the length specified by decoder is received intact.
Too long content is divided into multiple send issues Lengthfieldbasedframedecoder use