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();
        }
    }
}

相关推荐
字节源流5 小时前
关于maven的依赖下不下来的问题
java·maven
pjx9876 小时前
服务间的“握手”:OpenFeign声明式调用与客户端负载均衡
java·运维·spring·负载均衡
prinrf('千寻)6 小时前
MyBatis-Plus 的 updateById 方法不更新 null 值属性的问题
java·开发语言·mybatis
老华带你飞6 小时前
实习记录小程序|基于SSM+Vue的实习记录小程序设计与实现(源码+数据库+文档)
java·数据库·spring boot·小程序·论文·毕设·实习记录小程序
在未来等你7 小时前
互联网大厂Java求职面试:AI与大模型应用集成及云原生挑战
java·微服务·ai·kubernetes·大模型·embedding·spring ai
源码技术栈7 小时前
SaaS基于云计算、大数据的Java云HIS平台信息化系统源码
java·大数据·云计算·云his·his系统·云医院·区域his
编程、小哥哥7 小时前
互联网大厂Java面试:从Spring Boot到微服务架构的技术深挖
java·spring boot·redis·微服务·prometheus·面试技巧
揽你·入怀7 小时前
数据结构:ArrayList简单实现与常见操作实例详解
java·开发语言
okok__TXF7 小时前
SpringBoot3+AI
java·人工智能·spring
AA-代码批发V哥8 小时前
Math工具类全面指南
java·开发语言·数学建模