Saturday, September 22, 2018

Friday, September 7, 2018

ByteBuffer flip vs rewind

https://stackoverflow.com/questions/16461284/difference-between-bytebuffer-flip-and-bytebuffer-rewind


flip() makes it ready for write() (or for get())
         rewind() makes it ready for read() (or for put())

get() Example;
You might want to read data from the buffer (assuming that you had initially stored it in there)and use it for something else such as converting to a string and manipulate it for further use.
ByteBuffer buf = ByteBuffer.allocateDirect(80);
private String method(){
buf.flip();
byte[] bytes = byte[10]; //creates a byte array where you can place your data 
buf.get(bytes); //reads data from buffer and places it in the byte array created above
return bytes;
}
write() Example; After you have read data from socket channel into the buffer you might want to write it back to socket channel - assuming that you want to implement something like a server that echos same message received from client.
So you will read from channel to buffer and from buffer back to channel
SocketChannel socketChannel = SocketChannel.open();
...

ByteBuffer buf = ByteBuffer.allocateDirect(80);

int data = socketChannel.read(buf); // Reads from channel and places it into the buffer
while(data != -1){ //checks if not end of reading
buf.flip();        //prepares for writing
....
socketChannel.write(buf) // if you had initially placed data into buf and you want to read 
                         //from it so that you can write it back into the channel


  }