NIO编程从入门到...

小学生,用最简单的方式 写一个 NIO 服务端


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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;

public class Test {

    static Logger log = LoggerFactory.getLogger(Test.class);
    public static void main(String[] args) {

        try {

            // 开启 selector
            Selector selector = Selector.open();

            // 开启 ServerSocketChannel
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.bind(new InetSocketAddress("127.0.0.1",8888));
            serverSocketChannel.configureBlocking(false);

            // 将 channel 注册到 selector中。 ServerSocketChannel 只能注册 OP_ACCEPT 事件
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

            while (true) {

                // 监听 channel事件
                int select = selector.select();
                if (select == 0){
                    continue;
                }

                // 遍历 channel事件
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()){
                    SelectionKey key = iterator.next();

                    // 连接事件
                    if (key.isAcceptable()){
                        // 这里只能是 ServerSocketChannel
                        ServerSocketChannel channel = (ServerSocketChannel) key.channel();

                        // 获取 新的连接 channel
                        SocketChannel socketChannel = channel.accept();
                        socketChannel.configureBlocking(false);

                        // 设置 新的连接channel 关注的事件
                        // 关注 OP_READ
                        socketChannel.register(selector, SelectionKey.OP_READ);
                    }

                    // 读事件
                    if (key.isReadable()){
                        SocketChannel socketChannel = (SocketChannel) key.channel();
                        ByteBuffer attachment = ByteBuffer.allocate(1024);
                        socketChannel.read(attachment);
                        attachment.flip();
                        // 模拟业务处理时间
                        Thread.sleep(1000 * 3);

                        log.info(new String(attachment.array()).trim());
                        attachment.clear();
                        // 关注 OP_WRITE
                       socketChannel.register(selector,SelectionKey.OP_WRITE);
                    }

                    // 写事件
                    if (key.isWritable()){
                        SocketChannel socketChannel = (SocketChannel) key.channel();

                        // 模拟业务处理时间
                        Thread.sleep(1000 * 3);
                        socketChannel.write(ByteBuffer.wrap("hello,i am server".getBytes()));
                        // 关闭连接
                        key.cancel();
                        socketChannel.close();
                    }

                    // 移除
                    iterator.remove();
                }
            }
        }catch (Exception e){
            log.error("error " ,e);
        }
    }
}

初中生,开始想用多线程,但是写的有问题

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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;

public class Test {

    static Logger log = LoggerFactory.getLogger(Test.class);
    public static void main(String[] args) {

        try {

            // 开启 selector
            Selector selector = Selector.open();

            // 开启 ServerSocketChannel
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.bind(new InetSocketAddress("127.0.0.1",8888));
            serverSocketChannel.configureBlocking(false);

            // 将 channel 注册到 selector中。 ServerSocketChannel 只能注册 OP_ACCEPT 事件
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

            int i=0;
            while (true) {

                // 监听 channel事件
                int select = selector.select();
                if (select == 0){
                    continue;
                }
                Thread t = new Thread(() -> {
                    try {

                        /**
                         * 启用一个新的线程 来处理 channel 事件。
                         *
                         * 新建立的 客户端连接 SocketChannel ,也 注册到了 当前的 selector
                         *
                         * 那么,这个线程启动之后,主线程 的 selector.select() 一直 返回 0
                         */
                        doSelector(selector);
                    } catch (Exception e) {
                        log.error("doSelector error", e);
                    }
                });
                t.setName("doSelector-" + (i++));
                t.start();

            }
        }catch (Exception e){
            log.error("error " ,e);
        }
    }

    private static void doSelector(Selector selector) throws IOException, InterruptedException {
        // 遍历 channel事件
        Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
        while (iterator.hasNext()){
            SelectionKey key = iterator.next();

            // 连接事件
            if (key.isAcceptable()){
                // 这里只能是 ServerSocketChannel
                ServerSocketChannel channel = (ServerSocketChannel) key.channel();

                // 获取 新的连接 channel
                SocketChannel socketChannel = channel.accept();
                socketChannel.configureBlocking(false);

                // 设置 新的连接channel 关注的事件
                // 关注 OP_READ
                socketChannel.register(selector, SelectionKey.OP_READ);
            }

            // 读事件
            if (key.isReadable()){
                SocketChannel socketChannel = (SocketChannel) key.channel();
                ByteBuffer attachment = ByteBuffer.allocate(1024);
                socketChannel.read(attachment);
                attachment.flip();
                // 模拟业务处理时间
                Thread.sleep(1000 * 3);

                log.info(new String(attachment.array()).trim());
                attachment.clear();
                // 关注 OP_WRITE
               socketChannel.register(selector,SelectionKey.OP_WRITE);
            }

            // 写事件
            if (key.isWritable()){
                SocketChannel socketChannel = (SocketChannel) key.channel();

                // 模拟业务处理时间
                Thread.sleep(1000 * 3);
                socketChannel.write(ByteBuffer.wrap("hello,i am server".getBytes()));
                // 关闭连接
                key.cancel();
                socketChannel.close();
            }

            // 移除
            iterator.remove();
        }
    }
}

然后 初中生 开始 改进了,但是还有问题


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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;

public class Test {

    static Logger log = LoggerFactory.getLogger(Test.class);

    // 检测 线程启动情况
    static volatile boolean start = false;

    public static void main(String[] args) {

        try {

            // 开启 selector,只监听 客户端的连接事件
            Selector selector = Selector.open();

            // 开启 selector ,用来 监听 客户端的 读写事件
            Selector selector2 = Selector.open();

            // 开启 ServerSocketChannel
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.bind(new InetSocketAddress("127.0.0.1",8888));
            serverSocketChannel.configureBlocking(false);

            // 将 channel 注册到 selector中。 ServerSocketChannel 只能注册 OP_ACCEPT 事件
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

            int i=0;
            while (true) {

                // 监听 channel事件
                int select = selector.select();
                if (select == 0){
                    continue;
                }

                // 将 客户端的连接事件,注册到 selector2 中
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if (key.isAcceptable()) {
                        ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                        SocketChannel socketChannel = channel.accept();
                        socketChannel.configureBlocking(false);

                        /**
                         *  每次 接手到的 新的客户端连接 注册到 selector2 中,
                         *  第一个线程进来是好的,当有第二个连接进来时,main线程 被 block了。
                         *
                         *  main线程 和 doSelector-0 线程 同时 操作 selector2,存在线程安全问题
                         */
                        socketChannel.register(selector2, SelectionKey.OP_READ);
                    }

                    // 这个不要忘记
                    iterator.remove();
                }

                if (!start) {
                    Thread t = new Thread(() -> {
                        try {
                            /**
                             * 起一个 新的 线程,只用来处理 selector2中的 客户端的 读写事件
                             */
                            while (true){
                                int count = selector2.select();
                                if (count == 0){
                                    continue;
                                }
                                doSelector2(selector2);
                            }
                        } catch (Exception e) {
                            log.error("doSelector error", e);
                        }
                    });
                    t.setName("doSelector-" + (i++));
                    t.start();
                    start = true;
                }

            }
        }catch (Exception e){
            log.error("error " ,e);
        }
    }

    private static void doSelector2(Selector selector) throws IOException, InterruptedException {
        // 遍历 channel事件
        Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
        while (iterator.hasNext()){
            SelectionKey key = iterator.next();
            // 读事件
            if (key.isReadable()){
                SocketChannel socketChannel = (SocketChannel) key.channel();
                ByteBuffer attachment = ByteBuffer.allocate(1024);
                socketChannel.read(attachment);
                attachment.flip();
                // 模拟业务处理时间
                Thread.sleep(1000 * 3);

                log.info(new String(attachment.array()).trim());
                attachment.clear();
                // 关注 OP_WRITE
               socketChannel.register(selector,SelectionKey.OP_WRITE);
            }

            // 写事件
            if (key.isWritable()){
                SocketChannel socketChannel = (SocketChannel) key.channel();

                // 模拟业务处理时间
                Thread.sleep(1000 * 3);
                socketChannel.write(ByteBuffer.wrap("hello,i am server".getBytes()));
                // 关闭连接
                key.cancel();
                socketChannel.close();
            }

            // 移除
            iterator.remove();
        }
    }
}

终于,初中生 写出了 一个 线程 处理连接事件,一个线程 处理 读写事件的 NIO 服务端


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

public class Test {

    static Logger log = LoggerFactory.getLogger(Test.class);

    // 检测 线程启动情况
    static volatile boolean start = false;

    // 任务队列,保存 新的连接SocketChannel
    static BlockingQueue<Runnable> queue = new LinkedBlockingDeque();

    public static void main(String[] args) {

        try {

            // 开启 selector,只监听 客户端的连接事件
            Selector selector = Selector.open();

            // 开启 selector ,用来 监听 客户端的 读写事件
            Selector selector2 = Selector.open();

            // 开启 ServerSocketChannel
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.bind(new InetSocketAddress("127.0.0.1",8888));
            serverSocketChannel.configureBlocking(false);

            // 将 channel 注册到 selector中。 ServerSocketChannel 只能注册 OP_ACCEPT 事件
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

            int i=0;
            while (true) {

                // 监听 channel事件
                int select = selector.select();
                if (select == 0){
                    continue;
                }

                // 将 客户端的连接事件,注册到 selector2 中
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if (key.isAcceptable()) {
                        ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                        SocketChannel socketChannel = channel.accept();


                        // 将新的连接 放入 队列中
                        queue.add(()->{
                            try {
                                socketChannel.configureBlocking(false);
                                socketChannel.register(selector2, SelectionKey.OP_READ);
                            }catch (Exception e){
                                log.error("add error",e);
                            }

                        });

                        /**
                         * 为了 防止 与 selector2 绑定的 线程,在执行 selector2.select() 时 阻塞
                         * 这里需要 调用  selector2.wakeup(); 来唤醒
                         */
                        selector2.wakeup();
                    }

                    // 这个不要忘记
                    iterator.remove();
                }

                if (!start) {
                    Thread t = new Thread(() -> {
                        try {
                            /**
                             * 起一个 新的 线程,只用来处理 selector2中的 客户端的 读写事件
                             */
                            while (true){
                                /**
                                 * 用非阻塞的方法 从队列中拿任务,如果拿不到则立即返回。
                                 * 因为程序需要继续监听 已经注册到 selector2中的 事件
                                 */
                                Runnable take = queue.poll();
                                if (take != null){
                                    take.run();
                                }

                                /**
                                 * 如果 selector2中 一直 没有 事件发生,则 当前线程会一直 阻塞在这里
                                 * 当有新的连接请求进来时,即使 队列中 存在任务,也没办法处理。
                                 * 所以,需要在 有新连接请求时,执行 selector2.wakeup(); 来唤醒
                                 */
                                int count = selector2.select();
                                if (count == 0){
                                    continue;
                                }
                                doSelector2(selector2);
                            }
                        } catch (Exception e) {
                            log.error("doSelector error", e);
                        }
                    });
                    t.setName("doSelector-" + (i++));
                    t.start();
                    start = true;
                }

            }
        }catch (Exception e){
            log.error("error " ,e);
        }
    }

    private static void doSelector2(Selector selector) throws IOException, InterruptedException {
        // 遍历 channel事件
        Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
        while (iterator.hasNext()){
            SelectionKey key = iterator.next();
            // 读事件
            if (key.isReadable()){
                SocketChannel socketChannel = (SocketChannel) key.channel();
                ByteBuffer attachment = ByteBuffer.allocate(1024);
                socketChannel.read(attachment);
                attachment.flip();
                // 模拟业务处理时间
                Thread.sleep(1000 * 3);

                log.info(new String(attachment.array()).trim());
                attachment.clear();
                // 关注 OP_WRITE
               socketChannel.register(selector,SelectionKey.OP_WRITE);
            }

            // 写事件
            if (key.isWritable()){
                SocketChannel socketChannel = (SocketChannel) key.channel();

                // 模拟业务处理时间
                Thread.sleep(1000 * 3);
                socketChannel.write(ByteBuffer.wrap("hello,i am server".getBytes()));
                // 关闭连接
                key.cancel();
                socketChannel.close();
            }

            // 移除
            iterator.remove();
        }
    }
}

NIO 如果只用单线程 发挥不出 其优势,必须用多线程。

一个线程 处理 连接事件

一个线程处理 读写事件

还是比较容易:

处理连接事件的线程有一个自己的 selector。有新连接请求时,将 新的连接 包装成一个 任务,丢到 队列中,并且 唤醒 读写事件的 线程

读写事件的线程也有一个自己的 selector。从队列中拿任务,如果有,则执行任务,然后处理自己的 selector

各自维护 一个 selector,通过 任务队列 来 处理 新的 连接请求。同时注意, 从队列中拿任务时,不能 用 阻塞的方法。

那么,怎么才能更大的提高效率, 用多个 处理连接请求的 线程 和 多个 处理 读写请求的 线程 来完成 NIO 服务端呢?

高中生是这样做的...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值