The file pipe reads / adds invalid data

I am using byte buffer filechannel to send packets over the network. My problem is when the file-pipe reads the last few bytes, it adds the last bit of data from the previous bytes, even if I clear the byte buffer after I write.

For example,

Byte buffer size = 512 For the last iteration, the remaining bytes to send is 372. It reads the last 372 but also adds another 140 bytes (512-372) to the end of this and shows that the last 140 bytes were sent from the previous 512 bytes sent.

Here is my code:

ByteBuffer bBuffer = ByteBuffer.allocate(512);

while (fChannel.read(bBuffer) > 0) {

    bBuffer.flip();
    datagramChannel.write(bBuffer);
    bBuffer.clear();

    //omitted code
}

      

+3


source to share


1 answer


  • Using DatagramChannel

    this way will never work. You simply send chunks of a file that may or may not arrive, or arrive twice or more, in any order. Use TCP.

  • Even if it works magically and I have suspicions that there are additional errors or receive code in the "skipped code":

    while (fChannel.read(bBuffer) > 0) {
    
        bBuffer.flip();
        datagramChannel.write(bBuffer);
        bBuffer.clear();
    
        //omitted code
    }
    
          

    The correct version of the copy loop between pipes in Java is as follows:

    while (fChannel.read(buffer) > 0 || buffer.position() > 0) {    
        buffer.flip();
        datagramChannel.write(bBuffer);
        buffer.compact();
    }
    
          

    Note that you should keep writing while there is still something ( buffer.position() > 0

    ) in the buffer , and that you should compact()

    , not clear()

    so as not to assume that you have write()

    freed the buffer.

  • If not DatagramChannel

    , you must use a buffer that is much larger than 512, such as 8192.



+3


source







All Articles