基于Netty实现Web容器-Netty版Tomcat(二)

上次说到AIO,并做了开篇的简短介绍,今天接着聊
AIO,一种异步非阻塞IO
在这里回忆下前面所说的BIO和NIO,分别是同步阻塞IO和同步非阻塞IO,NIO在BIO的基础上实现了对于自身的一个非阻塞操作,然而对于程序来说,无论是是BIO或者是NIO,其过程依然是一个同步的过程,例如读写文件,程序进程在读写文件时,总是一个同步操作,需要读取/写入完毕或者发生异常时,才能做其他的事,类似下面过程:
在这里插入图片描述
前面聊天小程序也是一样,当客户端尝试连接服务端的时候,必须要等到服务端给出响应,那么客户端才结束方法的执行,即:
在这里插入图片描述
简言之,类似网页前端向服务端发起的AJAX请求,这是个客户端向服务端发送的一个 “同步的Ajax请求”。

那么AIO则提供了一个“异步的Ajax请求”,怎么理解这句话?读写文件或者TCP连接总是立马返回,不会存在同步等待。

即,读写文件变成这样:

在这里插入图片描述
聊天小程序,TCP连接成这样:
在这里插入图片描述
下面,以文件复制为例,代码说明下:

package com.lgli.aio.api;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;

/**
 * AioApi
 * @author lgli
 */
public class AioApi {





    public static void main(String[] args) throws Exception{
//        copyFileAsyncChannelByFuture();
        copyFileAsyncChannelByCompletionHandler();
    }


    /**
     * 异步复制文件二
     * @throws Exception
     */
    private static void copyFileAsyncChannelByCompletionHandler() throws Exception{
        //打开异步文件读取通道
        AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("F:\\entertainment\\movie\\马达加斯加的企鹅.mkv"),
                StandardOpenOption.READ);
        //打开异步文件写入通道
        AsynchronousFileChannel writeChannel = AsynchronousFileChannel.open(Paths.get("F:\\entertainment\\movie\\马达加斯加的企鹅-AIO-HAND.mkv"),
                StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE);
        ByteBuffer byteBuffer = ByteBuffer.allocate(1048576);
        long position = 0l;
        while(true){
            CountDownLatch downLatch = new CountDownLatch(1);
            channel.read(byteBuffer, position, byteBuffer, new CompletionHandler<Integer, ByteBuffer>() {
                @Override
                public void completed(Integer result, ByteBuffer attachment) {
                    downLatch.countDown();
                    System.out.println("读取完成");
                }

                @Override
                public void failed(Throwable exc, ByteBuffer attachment) {
                    System.err.println("读取失败");

                }
            });
            downLatch.await();
            byteBuffer.flip();
            CountDownLatch downLatchs = new CountDownLatch(1);
            writeChannel.write(byteBuffer, position, byteBuffer, new CompletionHandler<Integer, ByteBuffer>() {
                @Override
                public void completed(Integer result, ByteBuffer attachment) {
                    System.out.println("写入完成");
                    downLatchs.countDown();
                    byteBuffer.clear();
                }

                @Override
                public void failed(Throwable exc, ByteBuffer attachment) {
                    System.err.println("写入失败");
                }
            });
            position += byteBuffer.limit();
            downLatchs.await();
            System.out.println(writeChannel.size()+"-------"+channel.size());
            System.out.println(position);
            if(writeChannel.size() >= channel.size()){
                break;
            }
        }
        System.out.println("复制完成");
    }


    /**
     * 异步复制文件方式一
     * @throws Exception
     */
    private static void copyFileAsyncChannelByFuture() throws Exception{
        //打开异步文件读取通道
        AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("F:\\entertainment\\movie\\马达加斯加的企鹅.mkv"),
                StandardOpenOption.READ);
        //打开异步文件写入通道
        AsynchronousFileChannel writeChannel = AsynchronousFileChannel.open(Paths.get("F:\\entertainment\\movie\\马达加斯加的企鹅-AIO.mkv"),
                StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE);
        //分配一个指定大小的缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(2048);
        //读取通道开始读取数据
        //java.nio.channels.AsynchronousFileChannel.read(java.nio.ByteBuffer, long)
        //方法传入2个参数,第一个是缓冲区,第二个是开始读取的位置
        //方法执行立即返回结果,即不会等待是否读取完成,就返回了
        long begin = 0l;
        while(true){
            Future<Integer> read = channel.read(byteBuffer, begin);
            //可以通过方法java.util.concurrent.Future.isDone判断是否读取完成
            while(!read.isDone()){
                //这里是为了防止没有读取完数据,就执行后面的程序,所以这里属于瞎等待
                //实际可以根据场景在异步的同时做其他的事
                System.out.println("可以做其他事");
            }
            //读取完成
            //切换缓冲区读写方式
            long limit = byteBuffer.limit();
            byteBuffer.flip();
            //将数据写入
            Future<Integer> write = writeChannel.write(byteBuffer, begin);
            while(!write.isDone()){
                //这里是为了防止没有读取完数据,就执行后面的程序,所以这里属于瞎等待
                //实际可以根据场景在异步的同时做其他的事
                System.out.println("可以做其他事");
            }

            begin += limit;
            byteBuffer.clear();
            if(writeChannel.size() == channel.size()){
                //文件复制完成,退出
                break;
            }
        }
        System.out.println("复制完成");
    }


}

这里列举了AIO异步读写数据的两种方式,下面对代码做些简单的解释,有需要详细了解的,可查看:
https://mp.weixin.qq.com/s/5lOq0K24g17mklvCev3BQw
或者关注公众号查看更多内容:
在这里插入图片描述
AIO异步读写文件方式一<java.util.concurrent.Future>
copyFileAsyncChannelByFuture方法:
89-93行:打开读写异步文件通道AsynchronousFileChannel,一个是读,一个是写

95行:分配读写缓冲区

由于这里用较大文件复制作为示例,故没有分配足够大的缓冲区来一次读写完,所以选择循环读写,循环结尾123-126行,表示当文件复制后大小相等则复制完成,退出复制循环。

102行:异步读取文件数据,这个时候,程序立马返回结果,不管是否读取完成。返回对象为java.util.concurrent.Future

104-108行:可以通过java.util.concurrent.Future#isDone判断读取是否完成,如果没有完成,这里仅仅实例打印了一行文字–可以做其他的事,即在实际应用场景中,程序可以在读取文件的同时做其他的任何事,而不是同步阻塞在这里

112行:切换读写模式,变成写

114行-119行:和读取的意义一样,不做过多解释

121行:由于循环读取,这里需要一个参数来分批读取和写入数据

这里对API做点描述:
java.nio.channels.AsynchronousFileChannel#read(java.nio.ByteBuffer, long)

java.nio.channels.AsynchronousFileChannel#write(java.nio.ByteBuffer, long)

上述2个方法,需要传入2个参数,
在这里插入图片描述
第二个参数为读/写的位置,所以循环体中的参数begin就是来记录这个位置的

122行:清空缓冲区

最后文件复制完成。

AIO异步读写文件方式二<java.nio.channels.CompletionHandler>,回调方法处理,对应上述方法copyFileAsyncChannelByCompletionHandler

32-37行:打开读写异步文件通道AsynchronousFileChannel,一个是读,一个是写

38行:分配读写缓冲区

41行:定义CountDownLatch,这个是用来让线程等待,让其他线程执行完之后在执行的工具类,这里由于AIO读写异步操作,为了展示完整复制文件功能,所以用了这个工具,实际的项目中,除非特定情况,一般来说是不会让线程挂起的,所以这里仅仅为了这里的功能而使用

42-54行:读取文件,由于是异步的,所以在55行执行线程挂起,让读取文件操作完成后,再执行之后的代码。这里的读取文件方式,采用回调方法执行,即

java.nio.channels.CompletionHandler接口

这个接口有2个方法

java.nio.channels.CompletionHandler#completed

表示成功后执行的代码

java.nio.channels.CompletionHandler#failed

表示失败后执行的代码
读取文件变成了方法
java.nio.channels.AsynchronousFileChannel#read(

java.nio.ByteBuffer,

long,

A,

java.nio.channels.CompletionHandler<java.lang.Integer,? super A>)

需要传入4个参数:缓冲区,读取起始位置,附加IO操作对象《可以为空》,回调接口
在这里插入图片描述
45行代码,调用java.util.concurrent.CountDownLatch#countDown方法,告诉程序其他线程执行完毕<由于前面初始化CountDownLatch时,指定线程数为1,然后调用countDown减去1,则其他线程为0。即CountDownLatch只要其他线程为0时,当前线程就不再挂起了,继续执行后续程序>

56行:切换读写模式,变成写

58-70行:写入操作同读取,这里不再赘述

71行:记录读写文件位置

75-78行:复制完成,退出循环

下面,基于AIO的异步非阻塞操作,对前面的聊天小程序改造

服务端:


package com.lgli.aio.chart;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * AioChartService
 * @author lgli
 */
public class AioChartServer {


    public AioChartServer(int port) {
        try{
            //打开异步服务socket通道
            AsynchronousServerSocketChannel serverSocketChannel = AsynchronousServerSocketChannel.open();
            //绑定端口
            serverSocketChannel.bind(new InetSocketAddress(port));
            //保存连接的客户端
            List<AsynchronousSocketChannel> clients = new ArrayList<>();
            while(true){
                //监听连接
                CountDownLatch downLatch = new CountDownLatch(1);
                //获取到一个连接,则异步处理
                serverSocketChannel.accept(serverSocketChannel, new CompletionHandler<AsynchronousSocketChannel, AsynchronousServerSocketChannel>() {
                    @Override
                    public void completed(AsynchronousSocketChannel result, AsynchronousServerSocketChannel attachment) {
                        try{
                            //保存连接的客户端
                            clients.add(result);
                            //连接成功后,释放当前线程,持续等待下一个连接
                            downLatch.countDown();
                            //接收到连接
                            System.out.println("接收到"+result.getRemoteAddress()+"的连接");
                            //发送欢迎页到客户端
                            result.write(ByteBuffer.wrap(("欢迎"+result.getRemoteAddress()+"来到聊天室").getBytes()));
                            //读取和转发客户端发送的数据
                            //这是个持续的过程
                            while(true){
                                ByteBuffer byteBuffer = ByteBuffer.allocate(2048);
                                CountDownLatch c = new CountDownLatch(1);
                                result.read(byteBuffer, byteBuffer, new CompletionHandler<Integer, ByteBuffer>() {
                                    @Override
                                    public void completed(Integer intResult, ByteBuffer attachment) {
                                        if(intResult == null || intResult == 0){
                                            //没有数据读取
                                            c.countDown();
                                            return;
                                        }
                                        try{
                                            //打印服务端收到的数据
                                            byteBuffer.flip();
                                            byte[] bytes = new byte[byteBuffer.limit()];
                                            String receive = new String(byteBuffer.get(bytes,0,byteBuffer.limit()).array());
                                            System.out.println("服务端收到来自"+result.getRemoteAddress()+"的消息:"+receive);
                                            String sendMsg = result.getRemoteAddress()+":"+receive;
                                            //读取完数据后发送数据到其他客户端
                                            for(AsynchronousSocketChannel channel : clients){
                                                if(channel.getRemoteAddress().toString().equals(result.getRemoteAddress().toString())){
                                                    continue;
                                                }
                                                channel.write(StandardCharsets.UTF_8.encode(sendMsg));
                                            }
                                            byteBuffer.clear();
                                            c.countDown();
                                        }catch (Exception e){
                                            c.countDown();
                                            e.printStackTrace();
                                        }
                                    }

                                    @Override
                                    public void failed(Throwable exc, ByteBuffer attachment) {
                                        System.out.println("数据读取异常");
                                        exc.printStackTrace();
                                        c.countDown();
                                    }
                                });
                                c.await();
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void failed(Throwable exc, AsynchronousServerSocketChannel attachment) {
                        System.out.println("接收失败");
                    }
                });
                downLatch.await();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new AioChartServer(8080);
    }
}

客户端:

package com.lgli.aio.chart;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;

/**
 * AioChartClient
 * @author lgli
 */
public class AioChartClient {

    public AioChartClient(int port) {
        try{
            //打开异步通道
            AsynchronousSocketChannel socketChannel = AsynchronousSocketChannel.open();
            CountDownLatch downLatch = new CountDownLatch(1);
            //连接服务端
            socketChannel.connect(new InetSocketAddress("localhost", port),
                    socketChannel, new CompletionHandler<Void, AsynchronousSocketChannel>() {
                @Override
                public void completed(Void result, AsynchronousSocketChannel attachment) {
                    System.out.println("连接到服务器");
                    //连接完成后,执行接收服务端的消息和向服务端发送消息
                    //以下读取服务端数据和发送数据到服务端,是一个持续过程,这里用个循环
                    //由于需要持续读取服务端数据,这里又需要接收键盘数据的数据发送到服务端,这里另起一个线程去发送数据到客户端
                    Runnable runnable = ()->{
                        //向服务端发送数据
                        Scanner scan = new Scanner(System.in);
                        while(scan.hasNextLine()){
                            String sendMsg = scan.nextLine();
                            if("".equals(sendMsg)){
                                continue;
                            }
                            //发送数据到服务端
                            attachment.write(StandardCharsets.UTF_8.encode(sendMsg));
                        }
                    };
                    Thread thread = new Thread(runnable);
                    thread.start();
                    //持续读取服务端数据
                    while(true){
                        //读取服务端发送的数据
                        CountDownLatch downLatchs = new CountDownLatch(1);
                        ByteBuffer receive = ByteBuffer.allocate(2048);
                        attachment.read(receive, receive, new CompletionHandler<Integer, ByteBuffer>() {
                            @Override
                            public void completed(Integer result, ByteBuffer attachment) {
                                if(result == null || result == 0 || result == 17){
                                    //没有获取到服务端发送的数据
                                    //清空缓冲区
                                    downLatchs.countDown();
                                    receive.clear();
                                    return;
                                }
                                //切换读写模式
                                receive.flip();
                                byte[] bytes = new byte[receive.limit()];
                                //读取到服务端发送的数据
                                System.out.println(new String(receive.get(bytes,0,receive.limit()).array()));
                                //clear缓冲区
                                receive.clear();
                                downLatchs.countDown();
                            }
                            @Override
                            public void failed(Throwable exc, ByteBuffer attachment) {
                                System.out.println("读取客户端发送的数据异常");
                                downLatchs.countDown();
                                exc.printStackTrace();
                            }
                        });
                        try {
                            //每次接受数据完成后再接收下一次的数据
                            downLatchs.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void failed(Throwable exc, AsynchronousSocketChannel attachment) {
                    //打印连接失败
                    System.out.println("连接服务器失败");
                    exc.printStackTrace();
                    downLatch.countDown();
                }
            });
            downLatch.await();
            System.out.println("程序结束");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new AioChartClient(8080);

    }


}

对于上述代码,这里不做过多解释,每一步操作,基于前面的解释,都是可以理解的。

运行上述代码,可以达到一个简易AIO聊天室效果

对于Java IO的历史演变过程:BIO–>NIO–>NIO2(AIO),这里基本就告一段落了

可是主题貌似还没有进入

下期,将结合前面所有的东西,逐步过渡到主题上来,同时也开始Netty框架的正式学习篇

本次由于匆忙,所以文章可能有些地方未说得清楚,有需要清楚了解的,请查看公众号文章内容。那里比较详细

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值