I am new to Java NIO and not sure how to do things nio-ishly.
Suppose I read some data from a socket in ByteBuffer and used all the bytes, but one, using ByteBuffer get ByteBuffer . I know that the next thing will be four bytes with an integer in binary format, so I want to use getInt() , but only the first byte int is in the buffer.
It is natural for me to fill the buffer with a few more bytes from the connection, and then continue. If I understood correctly, I could achieve this with
buf.compact(); buf.position(buf.limit()); buf.limit(buf.capacity());
and then read more bytes.
Since there is no method with this behavior, but there is a flip() method, I wonder if my thinking is wrong. Are there any better ways to do this?
This situation will naturally happen, for example. if the connection provides a stream of length + data messages.
source share