Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clearing a ByteBuffer

Tags:

java

Very simple problem: I'm reading from one SocketChannel and would like to write the results to another SocketChannel. I'm using a Selector object, so I wait until one SocketChannel is readable, dump the data to a ByteBuffer, and then when the next SocketChannel is writable, I dump the ByteBuffer there. OK so far. However, it doesn't appear there is any way to actually "clear" a ByteBuffer, so I can't do any sort of check to know when new data has arrived.

I've tried the .clear() method, but that apparently doesn't clear the buffer, but just resets the buffer position to 1.

Here's some example code:

ByteBuffer channel1buf = ByteBuffer.allocate(1024);
ByteBuffer channel2buf = ByteBuffer.allocate(1024);

if (key.isReadable()) {
    if (key.channel().equals(channel1)) {
        channel1.read(channel2buf);
    } else if (key.channel().equals(channel2)) {
        channel2.read(channel1buf);
    }
} else if (key.isWritable()) {
    if (key.channel().equals(channel1) && channel1buf.asCharBuffer().length() > 0) {
        channel1.write(channel1buf);
        /* some way to clear channel1buf */
    } else /* same idea for channel2... */
}
like image 573
user1241397 Avatar asked Feb 29 '12 22:02

user1241397


People also ask

What is a ByteBuffer?

A ByteBuffer is a buffer which provides for transferring bytes from a source to a destination. In addition to storage like a buffer array, it also provides abstractions such as current position, limit, capacity, etc. A FileChannel is used for transferring data to and from a file to a ByteBuffer.

What is the byte order of ByteBuffer?

Access to binary dataThe initial order of a byte buffer is always BIG_ENDIAN . Corresponding methods are defined for the types char, short, int, long, and double. The index parameters of the absolute get and put methods are in terms of bytes rather than of the type being read or written.

What does ByteBuffer wrap do?

The wrap() method of java. nio. ByteBuffer Class is used to wraps a byte array into a buffer. The new buffer will be backed by the given byte array; that is, modifications to the buffer will cause the array to be modified and vice versa.


2 Answers

Buffer.clear resets the position, yes, and then you can use getPosition() > 0 to check if anything has been added to the buffer afterwards, no...?

like image 94
Louis Wasserman Avatar answered Oct 05 '22 14:10

Louis Wasserman


I resolved a same problem by this code, hope it can help you.

channel1buf.clear();
//zerolize buff manually
channel1buf.put(new byte[1024]);
channel1buf.clear();
like image 36
waveacme Avatar answered Oct 05 '22 14:10

waveacme