Adam Hughes Adam Hughes - 1 year ago 132
Java Question

Java Partial message handling from socket NIO ByteBuffer

I have a buffer that stores multiple messages. Say the buffer is 50 bytes (let me try to illustrate this with metacode)

-------------------- (50 byte empty buffer)

and my messages are of size 20. On a given socket read, I may get 1 message

|111111111|----------- (50 byte buffer with 1 20 byte message

Or two messages


But if I get three messages, I end up with a partial third message

|111111111|222222222|3333 (TRUNCATE)

On the next socketread, the rest of the third message comes through and the bytestream contains the second half of message 3:

33334444444455555555 ....

Furthermore, I know the position at which the third message starts, so I'd like to simply retain the contents of the third message in my buffer. I thought doing compact would be the case:

>>> readbuffer.compact()

And then simply pass this same buffer back into


And ideally, this would fill my buffer as so


However, I don't think that compacting and simply passing the readbuffer back into is the correct approach.

Is there a well-known solution for handling partial messages this way? I can think of a lot of things to try, but this has to be a common problem. I'd like to avoid the intermediary creation of buffers as much as possible, but can't think of a solution that doesn't invoke some sort of a residual buffer.


Answer Source

You are mistaken. Using compact() and then reusing the buffer for the next read() is exactly the correct approach.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download