user1241397
user1241397

Reputation: 103

Clearing a ByteBuffer

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... */
}

Upvotes: 10

Views: 27256

Answers (3)

vivek singh
vivek singh

Reputation: 21

IMO, allocation new memory(channel1buf.put(new byte[1024]);)

is not a better solution to follow.

You can use following code segment:

java.util.Arrays.fill(channel1buff.array(), (byte)0);

Upvotes: 2

waveacme
waveacme

Reputation: 331

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();

Upvotes: 6

Louis Wasserman
Louis Wasserman

Reputation: 198143

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...?

Upvotes: 8

Related Questions