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

相关推荐
xunyan62341 分钟前
第九章 JAVA常用类
java·开发语言
China_Yanhy17 分钟前
AWS S3 深度配置指南:每一栏每个选项有什么作用
java·数据库·aws
秃了也弱了。26 分钟前
FASTJSON库:阿里出品java界json解析库,使用与踩坑记录
java·开发语言·json
安全渗透Hacker39 分钟前
参数未校验导致的DOS(服务拒绝)问题典型场景
java·安全·web安全·网络安全·安全性测试
Chan161 小时前
微服务 - Higress网关
java·spring boot·微服务·云原生·面试·架构·intellij-idea
二哈喇子!1 小时前
JavaSE 与 JavaEE 知识点整合
java·servlet·tomcat
之歆1 小时前
Spring AI入门到实战到原理源码-多模型协作智能客服系统
java·人工智能·spring
yyy(十一月限定版)1 小时前
c++(3)类和对象(中)
java·开发语言·c++
IT 行者1 小时前
Spring Security 7 OAuth2 Token 格式选择浅析
java·后端·spring