【知识积累】BIO&NIO&AIO模型快速实战

本文源码:https://github.com/axin1240101543/netty(有什么问题可以提issue给我,一起学习,共同进步。)

一、BIO

1、BIOServer

package com.darren.service.netty.bio;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * <h3>netty</h3>
 * <p>BIO服务端</p>
 * 同步阻塞模型,一个客户端连接对应一个处理线程
 *
 * 缺点:
 * 1、IO代码里的accept、read操作是阻塞操作,如果连接不做数据读写操作会导致线程阻塞,浪费资源
 * 2、如果线程很多,会导致服务器线程太多,压力太大,比如C10k问题
 *
 * 应用场景:
 * BIO方式适用于连接数目比较小且固定的架构,这种方式对服务器资源要求比较高,但程序简单易理解
 *
 * 优化:可使用线程池
 *
 * @author : Darren
 * @date : 2021年05月21日 21:26:27
 **/
public class SocketServer {

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8080);
        while (true){
            System.out.println("等待连接...");
            //阻塞方法
            //接收客户端的连接,没有客户端连接就阻塞
            Socket clientSocket = serverSocket.accept();
            System.out.println("有客户端连接了...");
            handler(clientSocket);
            //优化
            /*ExecutorService executorService = Executors.newFixedThreadPool(30);
            executorService.submit(() -> handler(clientSocket));*/
        }
    }

    private static void handler(Socket clientSocket){
        byte[] bytes = new byte[1024];
        System.out.println("准备read...");
        //阻塞方法
        //接收客户端的数据,没有数据可读时就阻塞
        int length = 0;
        try {
            length = clientSocket.getInputStream().read(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("读取完毕...");
        if (length != -1){
            System.out.println("接收到客户端的数据:" + new String(bytes));
        }
        //给服务端输出HelloClient
        try {
            clientSocket.getOutputStream().write("HelloClient".getBytes());
            clientSocket.getOutputStream().flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

2、BIOClient

package com.darren.service.netty.bio;

import java.io.IOException;
import java.net.Socket;

/**
 * <h3>netty</h3>
 * <p>BIO客户端</p>
 *
 * @author : Darren
 * @date : 2021年05月21日 21:45:57
 **/
public class SocketClient {

    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("localhost", 8080);
        //向服务端发送数据
        socket.getOutputStream().write("HelloServer".getBytes());
        socket.getOutputStream().flush();
        System.out.println("向服务端发送数据结束");
        byte[] bytes = new byte[1024];
        //接收服务端回传的数据
        socket.getInputStream().read(bytes);
        System.out.println("接收到服务端的数据:" + new String(bytes));
        socket.close();
    }

}

二、NIO

1、NIOServer

package com.darren.service.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * <h3>netty</h3>
 * <p>NIO服务端</p>
 *
 * 同步非阻塞,服务器实现模式为一个线程可以处理多个请求(连接),客户端发送的连接请求都会注册到多路复用器selector上,多路复用
 * 器轮询到连接有IO请求就进行处理,JDK1.4开始引入。
 *
 * 缺点:
 * 1、外层循环会导致CPU100%
 * 2、如果连接数太多的话,会有大量的无效遍历,假如有10000个连接,其中只有1000个连接有写数据,但是由于其他9000个连接并
 * 没有断开,我们还是要每次轮询遍历一万次,其中有十分之九的遍历都是无效的,这显然不是一个让人很满意的状态。
 *
 *
 * 应用场景:
 * NIO方式适用于连接数目多且连接比较短(轻操作) 的架构, 比如聊天服务器, 弹幕系统, 服务器间通讯,编程比较复杂
 *

 * @author : Darren
 * @date : 2021年05月21日 22:13:55
 **/
public class NIOServer {

    private static List<SocketChannel> clientSocketList =  new ArrayList();

    public static void main(String[] args) throws IOException {
        //创建NIO ServerSocketChannel   和BIO的ServerSocket类似
        ServerSocketChannel serverSocket = ServerSocketChannel.open();
        serverSocket.socket().bind(new InetSocketAddress(8080));
        //配置ServerSocketChannel为非阻塞,如配置为阻塞,则和BIO一样
        serverSocket.configureBlocking(false);
        System.out.println("服务启动成功...");

        while (true){
            //非阻塞模式accept方法不会阻塞,否则会阻塞
            //NIO的非阻塞是有操作系统内部实现的,底层调用了linux内核的accept函数
            SocketChannel clientSocket = serverSocket.accept();
            if (clientSocket != null){
                System.out.println("连接成功...");
                //设置SocketChannel为非阻塞
                clientSocket.configureBlocking(false);
                //将客户端保存在List中
                clientSocketList.add(clientSocket);
            }

            //遍历所有客户端进行数据读取
            Iterator<SocketChannel> iterator = clientSocketList.iterator();
            while (iterator.hasNext()){
                SocketChannel sc = iterator.next();
                ByteBuffer byteBuffer = ByteBuffer.allocate(128);
                //非阻塞模式read方法不会阻塞,否则会阻塞
                int length = sc.read(byteBuffer);
                //如果有数据,把数据打印出来
                if (length > 0){
                    System.out.println("接收到消息:" + new String(byteBuffer.array()));
                }else if (length == -1){
                    //如果客户端断开连接,把SocketChannel从集合中去掉
                    iterator.remove();
                    System.out.println("客户端断开连接...");
                }
            }
        }
    }

}

2、使用多路复用器的NIOServer

package com.darren.service.netty.nio;

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;

/**
 * <h3>netty</h3>
 * <p>使用Selector的NIO服务端</p>
 *
 * NIO有三大核心组件:Channel(通道),Buffer(缓冲区),Selector(多路复用器)
 * 1、channel类似于流,每个channel对应一个buffer缓冲区,buffer底层就是个数组
 * 2、channel会注册到selector上,由selector根据channel读写事件的发生将其交由某个空闲的线程处理
 * 3、NIO的Buffer和channel都是既可以读也可以写
 *
 * NIO底层在JDK1.4版本是用linux的内核函数select()或poll()来实现,跟上面的NioServer代码类似,selector每次都会轮询所有的
 * sockchannel看下哪个channel有读写事件,有的话就处理,没有就继续遍历,JDK1.5开始引入了epoll基于事件响应机制来优化NIO。
 *
 * 总结:NIO整个调用流程就是Java调用了操作系统的内核函数来创建Socket,获取到Socket的文件描述符,再创建一个Selector
 * 对象,对应操作系统的Epoll描述符,将获取到的Socket连接的文件描述符的事件绑定到Selector对应的Epoll文件描述符上,进
 * 行事件的异步通知,这样就实现了使用一条线程,并且不需要太多的无效的遍历,将事件处理交给了操作系统内核(操作系统中断
 * 程序实现),大大提高了效率。
 *
 * @author : Darren
 * @date : 2021年05月23日 18:37:27
 **/
public class NIOSelectorServer {

    public static void main(String[] args) throws IOException {
        //创建NIO ServerSocketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(8080));
        //配置ServerSocketChannel为非阻塞
        serverSocketChannel.configureBlocking(false);

        //打开Selector处理Channel,即创建epoll
        Selector selector = Selector.open();
        //把ServerSocketChannel注册到selector上,并且selector对客户端accept连接操作感兴趣
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("服务启动成功");

        while (true){
            //阻塞等待需要处理的事件发生
            selector.select();

            //获取selector中注册的全部事件的SelectorKey实例
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();

            //遍历SelectionKey对事件进行处理
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();

                //如果是OP_ACCEPT事件,则进行连接获取和事件注册
                if (key.isAcceptable()){
                    ServerSocketChannel server = (ServerSocketChannel) key.channel();
                    SocketChannel clientSocketChannel = server.accept();
                    clientSocketChannel.configureBlocking(false);
                    //这里只注册的读事件,如果需要给客户端发送数据可以注册写事件
                    clientSocketChannel.register(selector, SelectionKey.OP_READ);
                    System.out.println("客户端连接成功...");
                 }else if (key.isReadable()){
                    SocketChannel clientSocketChannel = (SocketChannel) key.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(128);
                    int length = clientSocketChannel.read(byteBuffer);
                    //如果有数据,把数据打印出来
                    if (length > 0){
                        System.out.println("接收到消息:" + new String(byteBuffer.array()));
                    }else if (length == -1){
                        //如果客户端断开连接,关闭Socket
                        System.out.println("客户端断开连接...");
                        clientSocketChannel.close();
                    }
                }
                //从事件集合中删除本次处理的key,防止下次select重复处理
                iterator.remove();
            }
        }
    }

}

三、AIO

1、AIOServer

package com.darren.service.netty.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * <h3>netty</h3>
 * <p>AIO服务端</p>
 *
 * 异步非阻塞, 由操作系统完成后回调通知服务端程序启动线程去处理, 一般适用于连接数较多且连接时间较长的应用
 * 应用场景:
 * AIO方式适用于连接数目多且连接比较长(重操作)的架构,JDK7 开始支持
 *
 * @author : Darren
 * @date : 2021年05月23日 21:19:35
 **/
public class AIOServer {

    public static void main(String[] args) throws IOException, InterruptedException {
        final AsynchronousServerSocketChannel severSocketChannel = AsynchronousServerSocketChannel
                .open()
                .bind(new InetSocketAddress(8080));
        severSocketChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
            @Override
            public void completed(AsynchronousSocketChannel clientSocketChannel, Object attachment) {
                try {
                    System.out.println("客户端连接成功...ThreadName2:" + Thread.currentThread().getName());
                    //在此接收客户端连接,如果不写这行代码后面的客户端连接不上服务器
                    severSocketChannel.accept(attachment, this);
                    System.out.println("RemoteAddress:" + clientSocketChannel.getRemoteAddress());
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    clientSocketChannel.read(byteBuffer, byteBuffer, new CompletionHandler<Integer, ByteBuffer>() {
                        @Override
                        public void completed(Integer result, ByteBuffer buffer) {
                            System.out.println("ThreadName3:" + Thread.currentThread().getName());
                            buffer.flip();
                            System.out.println("接收到客户端的消息:" + new String(buffer.array(), 0, result));
                            clientSocketChannel.write(ByteBuffer.wrap("HelloClient".getBytes()));
                        }

                        @Override
                        public void failed(Throwable exc, ByteBuffer attachment) {
                            exc.printStackTrace();
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void failed(Throwable exc, Object attachment) {
                exc.printStackTrace();
            }
        });
        System.out.println("服务启动成功...ThreadName1:" + Thread.currentThread().getName());

        Thread.sleep(Integer.MAX_VALUE);
    }

}

2、AIOClient

package com.darren.service.netty.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.ExecutionException;

/**
 * <h3>netty</h3>
 * <p>AIO客户端</p>
 *
 * @author : Darren
 * @date : 2021年05月23日 21:43:12
 **/
public class AIOClient {

    public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
        AsynchronousSocketChannel socketChannel = AsynchronousSocketChannel.open();
        socketChannel.connect(new InetSocketAddress("127.0.0.1", 8080)).get();
        socketChannel.write(ByteBuffer.wrap("Hello Server".getBytes()));
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        Integer length = socketChannel.read(byteBuffer).get();
        if (length != -1){
            System.out.println("客户端接收信息:" + new String(byteBuffer.array(), 0, length));
        }

        Thread.sleep(Integer.MAX_VALUE);
    }

}

四、BIO、NIO、AIO对比

  BIO NIO AIO
IO模型 同步阻塞 同步非阻塞 异步非阻塞
编程难度 简单 复杂 复杂
可靠性
吞吐量

五、同步异步与阻塞非阻塞(举例)

老张爱喝茶,废话不说,煮开水。
出场人物:老张,水壶两把(普通水壶,简称水壶;会响的水壶,简称响水壶)。
1 老张把水壶放到火上,立等水开。(同步阻塞)
老张觉得自己有点傻
2 老张把水壶放到火上,去客厅看电视,时不时去厨房看看水开没有。(同步非阻塞)
老张还是觉得自己有点傻,于是变高端了,买了把会响笛的那种水壶。水开之后,能大声发出嘀~~~~的噪音。
3 老张把响水壶放到火上,立等水开。(异步阻塞)
老张觉得这样傻等意义不大
4 老张把响水壶放到火上,去客厅看电视,水壶响之前不再去看它了,响了再去拿壶。(异步非阻塞)
老张觉得自己聪明了。
所谓同步异步,只是对于水壶而言。
普通水壶,同步;响水壶,异步。
虽然都能干活,但响水壶可以在自己完工之后,提示老张水开了。这是普通水壶所不能及的。
同步只能让调用者去轮询自己(情况2中),造成老张效率的低下。
所谓阻塞非阻塞,仅仅对于老张而言。
立等的老张,阻塞;看电视的老张,非阻塞。

猜你喜欢

转载自blog.csdn.net/axin1240101543/article/details/117198804