34. Nio (selector (handling message boundary issues (attachment and expansion)))

Nio (selector (handle message boundary issues (attachment and expansion)))

Step 1: We determine the specific location of this ByteBuffer

Let's analyze it. We can't put our buffer into a global variable, because this means that our buffer is shared by all channels (we need a buufer to be used by a channel), so we use attachments here (Attachment) is the third parameter of our channel registration to the selector, this knowledge, in which the buffer is registered to the selector because the channel is also registered to our selector, then one channel uses one buffer (no matter how many times he reads it). To get this buffer, we only need to get key.attachment() from the key that manages this selector

 

Step 2: When do we expand capacity

Here we take an example to analyze, our previous improved code was read according to \n to compact (it can’t be moved), now we don’t read \n, we also want to move the data forward and execute positon After reading (let's go to the operation of compact, stupid ratio), so let's think about the positions of position (into the number of remaining unread bytes) and limit, if they are the same here, they all come to the end. Then we need to expand

! ! ! (Note that we flip() here, because our previous method compact has changed to write, so here we have to read)

 

The last key.attach(newBuffer) is to replace the content of the previous buffer with this new one (their essence is still a buffer)

test:

 

 

 

Guess you like

Origin blog.csdn.net/logtcm4/article/details/127821069