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

关于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);
        }
    }
好的,以下是一个简单的 NIO 服务端代码示例: ```java import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; public class NioServer { public static void main(String[] args) throws IOException { // 创建一个 Selector Selector selector = Selector.open(); // 创建一个 ServerSocketChannel,并绑定到指定端口 ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.socket().bind(new InetSocketAddress(8888)); serverSocketChannel.configureBlocking(false); // 将 ServerSocketChannel 注册到 Selector 上,关注 OP_ACCEPT 事件 serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); while (true) { // 阻塞等待事件发生 selector.select(); // 处理事件 Iterator<SelectionKey> iterator = selector.selectedKeys().iterator(); while (iterator.hasNext()) { SelectionKey key = iterator.next(); iterator.remove(); if (key.isAcceptable()) { // 处理 OP_ACCEPT 事件 ServerSocketChannel ssc = (ServerSocketChannel) key.channel(); SocketChannel sc = ssc.accept(); sc.configureBlocking(false); sc.register(selector, SelectionKey.OP_READ); } else if (key.isReadable()) { // 处理 OP_READ 事件 SocketChannel sc = (SocketChannel) key.channel(); ByteBuffer buffer = ByteBuffer.allocate(1024); int len = sc.read(buffer); if (len > ) { buffer.flip(); byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes); String message = new String(bytes, "UTF-8"); System.out.println("Received message: " + message); } else if (len == -1) { // 客户端关闭连接 sc.close(); } } } } } } ``` 以上是一个简单的 NIO 服务端代码示例,可以实现基本的客户端连接和消息读取功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值