• NIO Netty(四)


    1、Selector处理write事件

    1.1、一次无法写完

    • 非阻塞模式下,无法保证把 buffer 中所有数据都写入 channel,因此需要追踪 write 方法的返回值(代表实际写入字节数)
    • 用 selector 监听所有 channel 的可写事件,每个 channel 都需要一个 key 来跟踪 buffer,但这样又会导致占用内存过多,就有两阶段策略
      • 当消息处理器第一次写入消息时,才将 channel 注册到 selector 上
      • selector 检查 channel 上的可写事件,如果所有的数据写完了,就取消 channel 的注册
      • 如果不取消,会每次可写均会触发 write 事件
    服务端
    package com.jtc.test;
    
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.ServerSocketChannel;
    import java.nio.channels.SocketChannel;
    import java.nio.charset.Charset;
    import java.util.Iterator;
    
    public class Server2 {
        public static void main(String[] args) throws IOException {
            ServerSocketChannel ssc = ServerSocketChannel.open();
            ssc.configureBlocking(false);
            ssc.bind(new InetSocketAddress(8080));
    
            Selector selector = Selector.open();
            ssc.register(selector, SelectionKey.OP_ACCEPT);
    
            while(true){
                selector.select();
                Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
    
                while (iter.hasNext()) {
                    SelectionKey key = iter.next();
                    iter.remove();
                    if (key.isAcceptable()) {
                        SocketChannel sc = ssc.accept();
                        sc.configureBlocking(false);
                        SelectionKey sckey = sc.register(selector, SelectionKey.OP_READ);
                        // 1. 向客户端发送内容
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < 9000000; i++) {
                            sb.append("a");
                        }
                        ByteBuffer buffer = Charset.defaultCharset().encode(sb.toString());
                        int write = sc.write(buffer);
                        // 3. write 表示实际写了多少字节
                        System.out.println("实际写入字节:" + write);
    
    
                        // 4. 如果有剩余未读字节,才需要关注写事件
                        if (buffer.hasRemaining()) {
                            // read 001  +  write 100  == 101
                            // 在原有关注事件的基础上,多关注 写事件
                            sckey.interestOps(sckey.interestOps() + SelectionKey.OP_WRITE);
                            // 把 buffer 作为附件加入 sckey
                            sckey.attach(buffer);
                        }
                    } else if (key.isWritable()) {
                        ByteBuffer buffer = (ByteBuffer) key.attachment();
                        SocketChannel sc = (SocketChannel) key.channel();
                        int write = sc.write(buffer);
                        System.out.println("实际写入字节:" + write);
    
    
                        if ( !buffer.hasRemaining() ) { // 写完了
                            //只要向 channel 发送数据时,socket 缓冲可写,这个事件会频繁触发,
                            //因此应当只在 socket 缓冲区写不下时再关注可写事件,数据写完之后再取消关注
                            key.interestOps(key.interestOps() - SelectionKey.OP_WRITE);
                            key.attach(null);
                        }
                    }
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    客户端
    package com.jtc.test;
    
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.SocketChannel;
    import java.util.Iterator;
    
    public class Client2 {
        public static void main(String[] args) throws IOException {
            Selector selector = Selector.open();
            SocketChannel sc = SocketChannel.open();
            sc.configureBlocking(false);
            sc.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ);
            sc.connect(new InetSocketAddress("localhost", 8080));
            int count = 0;
            while (true) {
                selector.select();
                Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
                while (iter.hasNext()) {
                    SelectionKey key = iter.next();
                    iter.remove();
                    if (key.isConnectable()) {
                        //sc.finishConnect();
                        System.out.println(sc.finishConnect());
                    } else if (key.isReadable()) {
                        ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024);
                        count += sc.read(buffer);
                        buffer.clear();
                        System.out.println(count);
                    }
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37

    1.2、使用多线程优化

    前面的代码只有一个选择器,没有充分利用多核 cpu,改进:

    分两组选择器

    • 单线程配一个选择器,专门处理 accept 事件
    • 创建 cpu 核心数的线程,每个线程配一个选择器,轮流处理 read 事件
    服务端
    package com.jtc.test;
    import lombok.extern.slf4j.Slf4j;
    
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.ServerSocketChannel;
    import java.nio.channels.SocketChannel;
    import java.util.Iterator;
    import java.util.Set;
    import java.util.concurrent.ConcurrentLinkedQueue;
    import java.util.concurrent.atomic.AtomicInteger;
    
    import static com.jtc.Utils.ByteBufferUtil.debugAll;
    
    public class Server2re {
        public static void main(String[] args) throws IOException {
            new BossEventLoop().register();
        }
    
    
        @Slf4j
        static class BossEventLoop implements Runnable {
            private Selector boss;
            private WorkerEventLoop[] workers;
            private volatile boolean start = false;
            AtomicInteger index = new AtomicInteger();
    
            public void register() throws IOException {
                if (!start) {
                    ServerSocketChannel ssc = ServerSocketChannel.open();
                    ssc.bind(new InetSocketAddress(8080));
                    ssc.configureBlocking(false);
    
                    boss = Selector.open();
                    SelectionKey ssckey = ssc.register(boss, 0, null);
                    ssckey.interestOps(SelectionKey.OP_ACCEPT);
    
                    workers = initEventLoops();
    
                    new Thread(this, "boss").start();
                    log.debug("boss start...");
                    start = true;
                }
            }
    
            public WorkerEventLoop[] initEventLoops() {
                //根据CPU核心数分配员工个数
                //EventLoop[] eventLoops = new EventLoop[Runtime.getRuntime().availableProcessors()];
                WorkerEventLoop[] workerEventLoops = new WorkerEventLoop[2];
                for (int i = 0; i < workerEventLoops.length; i++) {
                    workerEventLoops[i] = new WorkerEventLoop(i);
                }
                return workerEventLoops;
            }
    
            @Override
            public void run() {
                while (true) {
                    try {
                        boss.select();
                        Iterator<SelectionKey> iter = boss.selectedKeys().iterator();
    
                        while (iter.hasNext()) {
                            SelectionKey key = iter.next();
                            iter.remove();
                            if (key.isAcceptable()) {
                                ServerSocketChannel c = (ServerSocketChannel) key.channel();
                                SocketChannel sc = c.accept();
                                sc.configureBlocking(false);
    
                                log.debug("{} connected", sc.getRemoteAddress());
                                workers[index.getAndIncrement() % workers.length].register(sc);
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    
        @Slf4j
        static class WorkerEventLoop implements Runnable {
            private Selector worker;
            private volatile boolean start = false;
            private int index;
    
            private final ConcurrentLinkedQueue<Runnable> tasks = new ConcurrentLinkedQueue<>();
    
            public WorkerEventLoop(int index) {
                this.index = index;
            }
    
            public void register(SocketChannel sc) throws IOException {
                if (!start) {
                    worker = Selector.open();
                    new Thread(this, "worker-" + index).start();
                    start = true;
                }
                tasks.add(() -> {
                    try {
                        SelectionKey sckey = sc.register(worker, 0, null);
                        sckey.interestOps(SelectionKey.OP_READ);
                        //不会阻塞,也就是不管有没有事件,立刻返回,自己根据返回值检查是否有事件
                        worker.selectNow();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
                worker.wakeup();
            }
    
            @Override
            public void run() {
                while (true) {
                    try {
                        worker.select();
                        Runnable task = tasks.poll();
                        if (task != null) {
                            task.run();
                        }
                        Set<SelectionKey> keys = worker.selectedKeys();
                        Iterator<SelectionKey> iter = keys.iterator();
                        while (iter.hasNext()) {
                            SelectionKey key = iter.next();
                            if (key.isReadable()) {
                                SocketChannel sc = (SocketChannel) key.channel();
                                ByteBuffer buffer = ByteBuffer.allocate(128);
                                try {
                                    int read = sc.read(buffer);
                                    if (read == -1) {
                                        key.cancel();
                                        sc.close();
                                    } else {
                                        buffer.flip();
                                        log.debug("{} message:", sc.getRemoteAddress());
                                        debugAll(buffer);
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                    key.cancel();
                                    sc.close();
                                }
                            }
                            iter.remove();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    客户端
    package com.jtc.test;
    
    import java.io.IOException;
    import java.net.Socket;
    
    public class Client1 {
        public static void main(String[] args) {
            try (Socket socket = new Socket("localhost", 8080)) {
                System.out.println(socket);
                StringBuilder sb = new StringBuilder();
    
                for (int i = 0; i < 300; i++) {
                    sb.append("c");
                }
                String s = sb.toString();
                socket.getOutputStream().write(s.getBytes());
                System.in.read();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    } 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    2、UDP

    • UDP 是无连接的,client 发送数据不会管 server 是否开启
    • server 这边的 receive 方法会将接收到的数据存入 byte buffer,但如果数据报文超过 buffer 大小,多出来的数据会被默默抛弃
    服务端
    public class UdpServer {
        public static void main(String[] args) {
            try (DatagramChannel channel = DatagramChannel.open()) {
                channel.socket().bind(new InetSocketAddress(9999));
                System.out.println("waiting...");
                ByteBuffer buffer = ByteBuffer.allocate(32);
                channel.receive(buffer);
                buffer.flip();
                debug(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    客户端
    public class UdpClient {
        public static void main(String[] args) {
            try (DatagramChannel channel = DatagramChannel.open()) {
                ByteBuffer buffer = StandardCharsets.UTF_8.encode("hello");
                InetSocketAddress address = new InetSocketAddress("localhost", 9999);
                channel.send(buffer, address);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
  • 相关阅读:
    从零开始学习wpsjs
    数字图像处理(入门篇)一 图像的数字化与表示
    P5117 [USACO18DEC]The Bucket List B
    分布式锁的三种实现方式
    BUUCTF【pwn】解题记录(4-6页持续更新中)
    产品经理技术脑:RESTful API
    drawio都能做那些事情和模板示例
    <哈希及模拟实现>——《C++高阶》
    CVPR 2022 论文和开源项目合集
    【开源免费】基于SpringBoot+Vue.JS网上购物商城(JAVA毕业设计)
  • 原文地址:https://blog.csdn.net/qq_42900213/article/details/126539144