Read and Write Int using ByteBuffer in Java NIO

bytebuffer, data-conversion, java, networking, nio

Solution

You have th flip() the buffer each time you swap from write to read and from read to writing. Add flip() to the second example after `receive()`

Once you have this working you should look at how you can re-use your ByteBuffers and EJP suggests.

Problem

I want to transmit an int array over a network using Datagram Channel in Java NIO API. However, the functions read/write can only take a `ByteBuffer` as an input. So I need to store the int data to a `ByteBuffer` and then read it back at the receiver. I am facing the `java.nio.BufferUnderflowException`. Here is what I do at the Sender Side: ``` for(i = 0; i < send_data.length; i++) { //Write the data onto Buffer ByteBuffer buffer1 = ByteBuffer.allocate(send_data[i].length*4); for(j = 0; j < send_data[i].length; j++) buffer1.putInt(send_data[i][j]); buffer1.flip(); //Transmit the data while(buffer1.hasRemaining()) channel.write(buffer1); } ``` Here, `send_data` is a 2D array where each row is treated as a separate data packet. At the Receiver Side ``` for(i = 0; i < k; i++) { ByteBuffer buffer = ByteBuffer.allocate((recvpkt[0].length)*4); channel.receive(buffer); j = 0; while(buffer.hasRemaining()) { recvpkt[i][j] = buffer.getInt(); j = j+1; } } ``` Similarly, `recvpkt` is a 2D array and each row of it will receive one packet from the network. I read that `getInt()` reads 4 bytes from the `ByteBuffer` and moves the current position by 4 bytes. Is it that I am using the `buffer.flip()` in a wrong manner. I am new to using `NIO` and am having difficulty in how to go about debugging such issues. UPDATE: The error no longer occurs. But now all that the Receiver gets is all zeros. Whereas I am transmitting a binary sequence in each packet. When I read back from the buffer at the Sender side itself, all the entries turn up correctly but the buffer received at Receiver side has all zeros. No idea why this is happening. UPDATE 2: Finally, after hours of struggling, the problem is fixed. When you receive the buffer , you need to rewind it. ``` channel.receive(buffer); buffer.rewind(); ``` If you now use the getInt method on the buffer, you will be able to read the buffer successfully.

Original source