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

相关推荐
hong_zc8 分钟前
JDBC 编程
java·数据库·mysql
Flying_Fish_roe9 分钟前
MyBatis-Plus 常见问题与优化
java·tomcat·mybatis
X² 编程说13 分钟前
14.面试算法-字符串常见算法题(三)
java·数据结构·后端·算法·面试
imc.111 小时前
初识linux(2)
java·linux·数据库
武子康1 小时前
大数据-143 - ClickHouse 集群 SQL 超详细实践记录!
java·大数据·数据库·分布式·sql·clickhouse·flink
巧手打字通1 小时前
解锁Java线程池:实战技巧与陷阱规避
java·性能优化·线程池
装不满的克莱因瓶1 小时前
【微服务】Eureka的自我保护机制
java·spring cloud·云原生·eureka·注册中心·服务注册
虫本初阳1 小时前
【Java】接口interface【主线学习笔记】
java·笔记·学习
繁依Fanyi1 小时前
828华为云征文|华为Flexus云服务器打造《我的世界》游戏服务器
java·服务器·开发语言·python·算法·华为·华为云
AskHarries1 小时前
Spring Boot集成Akka Cluster快速入门Demo
java·spring boot·后端·akka