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... */
}
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.
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.
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.
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...?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With