遇到一个比较有意思的NIO问题!

版权声明:自由转载,无需过问 https://blog.csdn.net/Next__One/article/details/78681995

关于NIO的ByteBuffer操作很多人都会,但有时候稍不注意就会犯错。比如:

private void doWrite(SocketChannel sc, String response) throws IOException {
        if (response != null && response.trim().length() > 0) {
            ByteBuffer buf = ByteBuffer.wrap(response.getBytes());
            buf.flip();
            sc.write(buf);
        }
    }

private void doWrite(SocketChannel channel, String response) throws IOException {
        if (response != null && response.trim().length() > 0) {
            byte[] bytes = response.getBytes();
            ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
            writeBuffer.put(bytes);
            writeBuffer.flip();
            channel.write(writeBuffer);
        }
    }

不仔细想,两个方法的效果看起来是一样的,而且上面一个更简单。
可是在运行时,会发现上面的实现却写不出来数据。
原因就出在ByteBuffer.flip()和ByteBuffer.wrap()连用了。
仔细读注释会发现:
wrap()方法
新的缓冲区将由给定的字节数组支持;也就是说,对缓冲区的修改会导致数组被修改,反之亦然。新的缓冲区的capacity和limit将是数组长度,它的position是0,它的mark将没有定义。它的支持数组将是给定数组,它的数组偏移>将为零。
capacity=limit=array.len;position=0
flip()方法,大家都很熟悉。
capacity:在读/写模式下都是固定的,就是我们分配的缓冲大小(容量)。
position:类似于读/写指针,表示当前读(写)到什么位置。
limit:在写模式下表示最多能写入多少数据,此时和capacity相同。在读模式下表示最多能读多少数据,此时和缓存中的实际数据大小相同。
这是源代码:

public final Buffer flip() {  
    limit = position;  
    position = 0;  
    mark = -1;  
    return this;  
}  

所以limit=0;position=0;
然后执行写入操作,就造成了写不进去数据的情况,因为写操作是从position到limit,但是他们都是0。
要想写进去数据也很简单,直接写buffer就可以了

private void doWrite(SocketChannel sc, String response) throws IOException {
        if (response != null && response.trim().length() > 0) {
            ByteBuffer buf = ByteBuffer.wrap(response.getBytes());
            sc.write(buf);
        }
    }

猜你喜欢

转载自blog.csdn.net/Next__One/article/details/78681995