非阻塞式 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 类中,并在遍历处理事件时创建新的线程来处理每个事件。这样可以实现并发处理不同连接的读写事件,提高系统的并发处理能力。

相关推荐
SailingCoder1 小时前
Go 线上偶发数据错乱:值拷贝、slice、并发 map 的识别与规避
开发语言·后端·golang
峥嵘life1 小时前
Android 17 具体代码新特性总结
android·开发语言·网络
HackTwoHub1 小时前
ARTEX 开源后继版本持续维护,AI 自主渗透测试系统保留完整能力12月持续更新
开发语言·人工智能·web安全·网络安全·开源·系统安全·php
Lethehong2 小时前
从轻点到落块:Rokid AIUI 游戏《叠叠乐》开发实践
java·开发语言·游戏
全速向光2 小时前
用 Three.js 从零打造一棵会发光的 3D 圣诞树
开发语言·javascript·3d
codeejun2 小时前
每日一Go·MySQL-28、账户转账事务设计
开发语言·mysql·golang
ShineWinsu3 小时前
对于Qt:QSS样式属性的解析
开发语言·c++·qt·面试·盒子模型·客户端·qss
reasonsummer3 小时前
【办公类-178-01】20261204医保需要“幼儿园园通学籍证明截图”(Python页面截图+转PDF)
开发语言·c#
夜雪轻寒3 小时前
AI 工具踩坑录:Prompt 我越写越长,模型反而越来越笨,删到第三版才明白它在装
java·开发语言·人工智能·语言模型·自然语言处理·prompt
Helix2503 小时前
JDK NIO网络编程实战:Channel、Buffer、Selector三大核心与非阻塞IO、Reactor模式完整指南
jdk·网络编程·nio·零拷贝·channel·buffer·selectorreactor