Java NIO: reading variable-sized blocks

I would like to read a line from a TCP stream that is specified with a byte length, followed by the actual data. In Python, I would do

length = ord(stream.read(1))
data = stream.read(length)

How to do the same in Java NIO? I have a buffer (capacity 257)

stream.read(buffer); // cannot specify a size here
int length = buffer.get();
byte[] data = new byte[length];
buffer.get(data);

Unfortunately, this does not work: calls to get () look at the data in the buffer: - (

I probably need a combination of flip, rewind, reset, etc., but I can't figure it out.

+3
source share
2 answers

if streamis SocketChannel, but bufferis ByteBuffer, you can do the following:

//assuming buffer is a ByteBuffer
buffer.position(0);
buffer.limit(1);
while (buffer.hasRemaining()) { 
   stream.read(buffer);
}
buffer.rewind();

//get the byte and cast it into the range 0-255
int length = buffer.get() & 0xFF;
buffer.clear();
buffer.limit(length);
while (buffer.hasRemaining()) { 
   stream.read(buffer);
}
buffer.rewind();
//the buffer is now ready for reading the data from
+5
source

, java.nio.channel.GatheringByteChannel DatagramChannel. .

, Python ( , ), (!).

- . . , , ( ). : , /.

0

Source: https://habr.com/ru/post/1715783/


All Articles