非阻塞式 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 中读取数据,然后将数据原样返回给客户端。

相关推荐
Wenweno0o1 天前
0基础Go语言Eino框架智能体实战-chatModel
开发语言·后端·golang
chenjingming6661 天前
jmeter线程组设置以及串行和并行设置
java·开发语言·jmeter
cch89181 天前
Python主流框架全解析
开发语言·python
不爱吃炸鸡柳1 天前
C++ STL list 超详细解析:从接口使用到模拟实现
开发语言·c++·list
十五年专注C++开发1 天前
RTTR: 一款MIT 协议开源的 C++ 运行时反射库
开发语言·c++·反射
Momentary_SixthSense1 天前
设计模式之工厂模式
java·开发语言·设计模式
‎ദ്ദിᵔ.˛.ᵔ₎1 天前
STL 栈 队列
开发语言·c++
勿忘,瞬间1 天前
数据结构—顺序表
java·开发语言
张張4081 天前
(域格)环境搭建和编译
c语言·开发语言·python·ai
weixin_423533991 天前
【Windows11离线安装anaconda、python、vscode】
开发语言·vscode·python