A very simple problem: I am reading one SocketChannel and would like to write the results in another SocketChannel. I use the Selector object, so I wait until one SocketChannel is readable, upload the data to ByteBuffer, and then when the next SocketChannel is writable, I unload ByteBuffer. Still. However, there seems to be no way to “clear” ByteBuffer, so I cannot do any checks to know when the new data arrived.
I tried the .clear () method, but apparently it does not clear the buffer, but simply resets the buffer position to 1.
I never program in Java so naked with me if this is a problem with the "obvious" solution ...
Here is a sample 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);
} else
}
Thank!
source
share