非阻塞式 I/O 模型的工作原理【NIO】

非阻塞式 I/O(Non-blocking I/O,NIO)是一种改进的 I/O 模型,引入了通道(Channel)和缓冲区(Buffer)的概念。相比于阻塞式 I/O,非阻塞式 I/O 允许在进行读/写操作时不会导致线程阻塞,而是立即返回,如果数据没有准备好,方法会返回一个特殊的值(通常是零),表示操作无法立即完成。在非阻塞式 I/O 中,一个线程可以管理多个连接,通过选择器(Selector)实现多路复用,从而提高了系统的并发能力和性能。

特点:

  1. 通道和缓冲区:非阻塞式 I/O 引入了通道和缓冲区的概念,通过通道进行数据的读写,而不是直接对流进行操作,这样可以提高效率。

  2. 选择器(Selector):非阻塞式 I/O 使用选择器实现多路复用,一个线程可以同时管理多个通道,当有数据可读写时,选择器会通知线程进行相应的操作,避免了线程阻塞。

  3. 立即返回:非阻塞式 I/O 的读/写操作不会导致线程阻塞,如果数据没有准备好,方法会立即返回,可以继续执行其他任务,提高了系统的并发能力。

适用场景:

非阻塞式 I/O 适用于高并发、大量连接的场景,能够提高系统的吞吐量和性能。例如,网络服务器、聊天程序、实时数据传输等场景都可以使用非阻塞式 I/O 来实现。

示例:

下面是一个简单的使用非阻塞式 I/O 的示例,使用 Java NIO 实现一个简单的 Echo 服务器,即将客户端发送的消息原样返回给客户端:

复制代码
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;
import java.util.Set;

public class NonBlockingServer {
    public static void main(String[] args) throws IOException {
        // 创建 Selector
        Selector selector = Selector.open();

        // 创建 ServerSocketChannel 并绑定端口
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(8080));
        serverSocketChannel.configureBlocking(false);

        // 将 ServerSocketChannel 注册到 Selector 上,并指定监听事件为接受连接事件
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        System.out.println("Server started, listening on port 8080...");

        while (true) {
            // 阻塞等待事件发生
            selector.select();

            // 获取发生事件的 SelectionKey 集合
            Set<SelectionKey> selectedKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectedKeys.iterator();

            // 遍历处理事件
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();

                // 处理接受连接事件
                if (key.isAcceptable()) {
                    ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
                    SocketChannel clientChannel = serverChannel.accept();
                    clientChannel.configureBlocking(false);
                    clientChannel.register(selector, SelectionKey.OP_READ);
                    System.out.println("Client connected: " + clientChannel.getRemoteAddress());
                }

                // 处理读事件
                if (key.isReadable()) {
                    SocketChannel clientChannel = (SocketChannel) key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    int bytesRead = clientChannel.read(buffer);
                    if (bytesRead != -1) {
                        buffer.flip();
                        byte[] bytes = new byte[buffer.remaining()];
                        buffer.get(bytes);
                        String message = new String(bytes);
                        System.out.println("Received message from client: " + message);

                        // 原样返回给客户端
                        clientChannel.write(ByteBuffer.wrap(bytes));
                    } else {
                        // 客户端关闭连接
                        key.cancel();
                        clientChannel.close();
                        System.out.println("Client disconnected: " + clientChannel.getRemoteAddress());
                    }
                }
            }
        }
    }
}

在这个示例中,我们首先创建了一个 Selector 对象,然后创建了一个 ServerSocketChannel 并绑定到指定端口,将其注册到 Selector 上,并指定监听事件为接受连接事件。在循环中,调用 select() 方法阻塞等待事件发生,一旦有事件发生,通过遍历 selectedKeys 处理相应的事件。当有客户端连接进来时,将客户端的 SocketChannel 注册到 Selector 上,并指定监听事件为读事件。在读事件发生时,从 SocketChannel 中读取数据,然后将数据原样返回给客户端。

相关推荐
白夜11177 小时前
C++任务调度与状态机
开发语言·c++·笔记
南宫萧幕7 小时前
MATLAB/Simulink 从零打通:HEV 能量管理 GA 联合仿真保姆级建模指南
开发语言·算法·matlab·汽车·控制·pid
Ulyanov7 小时前
基于 Python 的三维动态导弹攻防演示系统设计与实现:从架构到实战的深度剖析
开发语言·python·qt·架构·雷达电子对抗
苍煜7 小时前
Java自定义注解-SpringBoot实战
java·开发语言·spring boot
XS0301067 小时前
Java ArrayList
java·开发语言
暴力求解7 小时前
Linux---保存信号
linux·运维·服务器·开发语言·操作系统
钝挫力PROGRAMER7 小时前
贫血模型的改进
java·开发语言·设计模式·架构
lsx2024067 小时前
AngularJS 事件处理机制详解
开发语言
小书房7 小时前
Kotlin的内联函数
java·开发语言·kotlin·inline·内联函数
码农阿豪7 小时前
Python 操作金仓数据库的完全指南(上篇):连接管理与高可用
开发语言·数据库·python