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

优化上一篇文上的代码。

复制代码
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
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();

                // 创建新线程处理事件
                new Thread(new EventHandler(key)).start();
            }
        }
    }

    // 处理事件的线程类
    static class EventHandler implements Runnable {
        private SelectionKey key;

        public EventHandler(SelectionKey key) {
            this.key = key;
        }

        @Override
        public void run() {
            try {
                // 处理接受连接事件
                if (key.isAcceptable()) {
                    ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
                    SocketChannel clientChannel = serverChannel.accept();
                    clientChannel.configureBlocking(false);
                    clientChannel.register(key.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());
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

在这个优化后的代码中,我们将处理事件的逻辑封装在 EventHandler 类中,并在遍历处理事件时创建新的线程来处理每个事件。这样可以实现并发处理不同连接的读写事件,提高系统的并发处理能力。

相关推荐
Hello_WOAIAI2 分钟前
2.4 python装饰器在 Web 框架和测试中的实战应用
开发语言·前端·python
搬山.摧城8 分钟前
线程池和单例模式
开发语言·单例模式
百锦再12 分钟前
第1章 Rust语言概述
java·开发语言·人工智能·python·rust·go·1024程序员节
一叶之秋141222 分钟前
QT背景介绍与环境搭建
开发语言·qt
java1234_小锋32 分钟前
PyTorch2 Python深度学习 - 模型保存与加载
开发语言·python·深度学习·pytorch2
ACP广源盛139246256731 小时前
(ACP广源盛)GSV2231---DisplayPort 1.4 MST 到 HDMI 2.0/DP/Type-C 转换器(带嵌入式 MCU)
c语言·开发语言·单片机·嵌入式硬件·音视频·mst
quant_19861 小时前
【教程】使用加密货币行情接口 - 查询比特币实时价格
开发语言·后端·python·websocket·网络协议
熊猫_豆豆1 小时前
Python 写一个标准版和程序员版计算器
开发语言·python·计算器
Mr.Jessy1 小时前
Web APIs 学习第四天:DOM事件进阶
开发语言·前端·javascript·学习·ecmascript
studyForMokey1 小时前
【Kotlin内联函数】
android·开发语言·kotlin