The stream in Java is divided into a byte stream or a character stream, which is generally more convenient to use with character streams. Byte stream processing is relatively troublesome, socketchannel the data into the Bytebuffer, how to remove the full line of data (using CRLF delimited)?
For example:
The socket receives the following:
1234567890CRLF
0123456789CRLF
Note: CRLF is the carriage return newline symbol.
If you use Socketchannel.read (Bytebuffer buff) to read the data, if the buff's capatity is 12, then the first reading of the data is "1234567890CRLF" just a row, However, if the buff's capatity is less than 12, it will read more than two times to read the CRLF carriage return newline symbol. If Buff.capatity is greater than 12, then the data from the second row is read, and the next read operation, how to process the first read-more data? This problem is similar to the "push-back flow".
To resolve this issue, and to implement a feature similar to "push-back flow". Establish the following processing model
The Source, cursor interface implements reading bytes from the channel and implements a push-back function.
The Source.ready () function returns data that has been read from the channel. If there is data in buffer, return the remaining number of itself in buffer, and if the bytes in buffer have already been read, re-read the data from the channel into buffer. If no data can be read, then 1 is returned;
Source.ready (byte[] DST, int off, int len) function reads data into DST in buffer.
The source.reset (int len) function implements fallback at the buffer level, which is set buffer.position.
The cursor interface further encapsulates the source interface, while providing a push function that expands the reset's push-back functionality.
Cursor.push (byte[] src, int off, int len) pushes the data in byte[] back into the cursor, and the next read operation will read the data pushed in.
The consumer interface uses the consumer function to read data from the cursor and handle it accordingly. The data in the cursor is processed by inheriting the consumer interface according to different business logic.
Java Socketchannel processing model for reading Bytebuffer bytes