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