清除ByteBuffer [英] Clearing a ByteBuffer

查看:692
本文介绍了清除ByteBuffer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

非常简单的问题:我正在从一个SocketChannel读取,并希望将结果写入另一个SocketChannel。我正在使用Selector对象,所以我等到一个SocketChannel可读,将数据转储到ByteBuffer,然后当下一个SocketChannel可写时,我将ByteBuffer转储到那里。好到目前为止。但是,似乎没有任何方法可以实际清除ByteBuffer,因此我无法进行任何检查以了解新数据何时到达。



<我尝试过.clear()方法,但显然没有清除缓冲区,只是将缓冲区位置重置为1.



这里有一些例子代码:

  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);
}
}否则if(key.isWritable()){
if(key.channel()。equals(channel1)&& channel1buf.asCharBuffer()。length()> ; 0){
channel1.write(channel1buf);
/ *某种方式来清除channel1buf * /
}其他/ *同样的想法为channel2 ... * /
}


解决方案

Buffer.clear 重置位置,是的,然后您可以使用 getPosition()> 0 检查之后是否有任何事情被添加到缓冲区中,没有...?


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

解决方案

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

这篇关于清除ByteBuffer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆