10.处理write写事件

java 复制代码
@Slf4j
public class NioServer {

    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        Selector selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        serverSocketChannel.bind(new InetSocketAddress(8000));
        while (true) {
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            if(iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                iterator.remove();
                //与客户端建立连接
                if(selectionKey.isAcceptable()) {
                    //因为ServerSocketChannel只有一个,可以直接使用
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    SelectionKey acceptKey = socketChannel.register(selector, 0, null);
                    acceptKey.interestOps(SelectionKey.OP_READ);

                    //向客户端发大量数据
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < 5000000; i++) {
                        sb.append("a");
                    }
                    ByteBuffer byteBuffer = StandardCharsets.UTF_8.encode(sb.toString());

                    //返回实际写的字节数
                    int write = socketChannel.write(byteBuffer);
                    log.info("write1={}", write);
                    if(byteBuffer.hasRemaining()) {
                        //添加关注写事件
                        acceptKey.interestOps(acceptKey.interestOps() + SelectionKey.OP_WRITE);
                        //把未写完的数据挂到selectKey上
                        acceptKey.attach(byteBuffer);
                    }
                } else if(selectionKey.isWritable()) {
                    ByteBuffer byteBuffer = (ByteBuffer)selectionKey.attachment();
                    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                    int write = socketChannel.write(byteBuffer);
                    log.info("write2={}", write);
                    //清理操作
                    if(!byteBuffer.hasRemaining()) {
                        selectionKey.attach(null);//清除附件ByteBuffer
                        //不需要关注write事件
                        selectionKey.interestOps(selectionKey.interestOps() - SelectionKey.OP_WRITE);
                    }
                }
            }
        }
    }
}
java 复制代码
@Slf4j
public class NioClient {

    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress("localhost", 8000));

        long totalCount = 0;
        while (true) {
            ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1024 * 1024);
            int read = socketChannel.read(byteBuffer);
            totalCount += read;
            log.info("totalCount={}", totalCount);
            byteBuffer.clear();
        }
    }
}

相关推荐
leikooo8 小时前
用餐厅和盘子理解栈和堆
java·数据结构·链表·rust
Ivanqhz9 小时前
激活函数在 Transformer 中的作用及各种变体简述
java·linux·数据库·人工智能·深度学习
沙漠之主10 小时前
C++编程教学设计资料:从入门到实战的完整课程方案
java·前端·c++
FPGA小徐10 小时前
PA1 基础设施(2)深度解析:NEMU 中 ITRACE、MTRACE、FTRACE、IRINGBUF、ETRACE、DIFFTEST 全解析
java·服务器·网络
YOLO数据集集合10 小时前
EvoAgent:面向PR研发治理的自进化Multi-Agent Harness系统
java·开发语言·目标检测·agent·自进化
知行EDI11 小时前
知行之桥 MaBang 端口使用指南——Create Order 订单创建篇
java·服务器·数据库
笑鸿的学习笔记11 小时前
C++笔记之大块顺序写
java·c++·笔记
打工仔折腾 AI11 小时前
从 Demo 到生产级 Agent:8 个关键设计机制与 Python 实现拆解
java·jvm·人工智能·后端·python·langchain·ai agent 实战
殷色玫瑰12 小时前
C/C++ 内存管理详解:从内存分布到 new/delete 底层原理
java·linux·c语言·c++
青山木13 小时前
Hot 100 --- 编辑距离
java·数据结构·算法·leetcode·动态规划