views:

15

answers:

1

I am building a non blocking server using javas NIO package, and have a couple questions about validating received data.

I have noticed that when i call read on a socket channel, it will attempt to fill the byte buffer that it is reading to (as per the documentation). When i send 10 bytes to the server from the client, the server will read the those ten bytes into the byte buffer, the rest of the bytes in the byte buffer will stay at zero, and the number returned from the read operation will be the size of my byte buffer even though the client only wrote 10 bytes.

What i am trying to figure out is if there is a way to get just the number of bytes the client sent to the server when the server reads from a socket channel (in the above case, 10 instead of 1024).

If that doesn't work i know i can get separate all the actual received data from the client from this 'excess' data stored in the byte buffer by using delimiters in conjunction with my 'instruction set headers' and what not, but it seems like this should exists so i have to wonder if i am just missing something obvious, or if there is some low level reason why this can't be done.

Thanks :)

+1  A: 

you probably forgot to call the notorious flip() on your buffer.

buffer.clear();
channel.read(buffer);
buffer.flip();
// now you can read from the buffer
buffer.get...

I need to change my signature to nio.sucks

irreputable
Ga!! You are right, i feel like a complete fool now!Thanks
kyeana