Http://scholers.iteye.com/blog/730429
We know that during socket TCP/IP communication, we don't know how long the packets are received each time? That is, the boundary of a message cannot be determined.
There are several common practices:
1. Set a fixed-length header to add a message length to a fixed header. Read the message header first to obtain the overall length of the message.
2. Set special characters in the message as the boundary. For example:
***************************
And other special symbols.
In mina2 (my version is mina2 RC1), I use the first method to read the message.
Code: You can use the prefixeddataavailable method of iobuffer to get the message header. Unfortunately, after reading the source code of mina2, the parameters of the prefixeddataavailable method are only 1, 2, and 4, that is to say, only 1, 2, 4-bit message header. If you are using a custom message header, It is not supported. However, you can modify the mina2 source code to meet your special requirements.
The statement is as follows:
Java code
- F (in. prefixeddataavailable (4) {// determine whether a 4-byte message header exists
- Int length = in. getint ();
- Byte [] bytes = new byte [length];
- In. Get (bytes );
In mina2, when starting a server, you need to set the length of the initialization buffer. If this value is not set, it seems that the default value is 2048, when the message sent from the client exceeds the set value, the mina2 Mechanism accepts messages in segments and reads the characters in the buffer zone. Therefore, when reading the message, determine the number of times.
Java code
- Final ioacceptor acceptor = new niosocketacceptor ();
- Cceptor. getsessionconfig (). setreadbuffersize (2048 );
In this case, how many times can we determine that only one complete message is received? One way is to segment your data into the session, read from the session each time, until the read is complete, and then perform decoding-business operations. Since mina2 solves the communication problem, we only need to care about the decoding problem.