I would like to read a string from a TCP stream that is given with a byte length followed by the actual data. In Python, I would do
length = ord(stream.read(1))
data = stream.read(length)
How do I do the same in Java NIO? What I have is a buffer (of capacity 257)
stream.read(buffer); // cannot specify a size here
int length = buffer.get();
byte[] data = new byte[length];
buffer.get(data);
Unfortunately, this doesn't work: the get() calls read past the data in the buffer :-(
I probably need some combination of flip, rewind, reset, etc., but I can't figure it out.