Netty4核心原理学习之JAVA AIO初体验

1、AIO基本原理

AIO(异步I/0 把I/O读写操作完全交给操作系统),重要的三分分类分别为:AsychronousServerSocketChannel(服务端)、AsynchronousSocketChannel(客户端)、CompletionHandler(用户处理器)

2、AIO初体验(感受服务端和客户端的交互过程)

package com.sckj.netty.netty.AIO;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.ArrayList;
import java.util.List;

/*
 * 功能描述: <br>
 * 〈AIO客户端 发送一串字符串到服务端,同时在CompletionHandler接口处理服务端发送过来的结果〉
 * @Param:
 * @Return:
 * @Author: 
 * @Date: 2021/3/22 16:09
 */
public class AIOClinent {
    private AsynchronousSocketChannel client;

    public AIOClinent() throws Exception {
        //开启客户端
        client = AsynchronousSocketChannel.open();
    }

    public void connect(String host, int port) throws Exception {
        //attachment指要附加到I/O操作的对象
        client.connect(new InetSocketAddress(host, port), null, new CompletionHandler<Void, Void>() {
            @Override
            public void completed(Void result, Void attachment) {
                try {
                    //把一个byte数组或byte数组的一部分包装成ByteBuffer
                    client.write(ByteBuffer.wrap("这是一条测试数据".getBytes())).get();
                    System.out.println("已发送到服务器");
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println(e.toString());
                }
            }

            @Override
            public void failed(Throwable exc, Void attachment) {
                exc.printStackTrace();
            }
        });
        final ByteBuffer bb = ByteBuffer.allocate(1024);
        client.read(bb, null, new CompletionHandler<Integer, Object>() {
            @Override
            public void completed(Integer result, Object attachment) {
                System.out.println("I/O操作完成" + result);
                System.out.println("获取返回结果" + new String(bb.array()));
            }

            @Override
            public void failed(Throwable exc, Object attachment) {
                exc.printStackTrace();
            }
        });
        try {
            Thread.sleep(Integer.MAX_VALUE);
        } catch (InterruptedException e) {
            System.out.println(e);
        }
    }

    public static void main(String[] args) throws Exception {
        new AIOClinent().connect("localhost", 8000);
    }
}

package com.sckj.netty.netty.AIO;

import javax.sound.midi.Soundbank;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/*
 * 功能描述: <br>
 * 〈AIO服务端  主要功能就是开启一个监听端口,然后在CompletionHandler中处理接收到的消息后的逻辑,将接收到的信息在输出到客户端〉
 * @Param:
 * @Return:
 * @Author: 
 * @Date: 2021/3/22 15:22
 */
public class AIOServer {
    private final int port;

    public AIOServer(int port) {
        this.port = port;
        listen();
    }

    //监听服务
    private void listen() {
        try {
            //创建一个线程池
            //newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
            ExecutorService executorService = Executors.newCachedThreadPool();
            //创建具有给定线程池的异步通道组。
            //每一个asynchronous channel都属于同一个group,共享一个Java线程池
            //AsynchronousChannelGroup其内部其实是一个(一些)线程池来进行实质工作的;
            // 而他们干的活就是等待IO事件,处理数据,分发各个注册的completion handlers。
            //initialSize参数作为其可以提交的初始任务数的提示
            AsynchronousChannelGroup threadGroup = AsynchronousChannelGroup.withCachedThreadPool(executorService, 1);
            //AsynchronousServerSocketChannel还是AsynchronousSocketChannel的创建都使用各自的静态方法open,
            // 而open方法便需要asynchronousChannelGroup。
            //创建AIO服务通道
            final AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open(threadGroup);
            //InetSocketAddress创建IP地址为通配符地址的套接字地址端口号为指定值。
            server.bind(new InetSocketAddress(port));
            System.out.println("服务已启动,监听端口" + port);
            //server.accept此方法是用户当一个新的连接产生时,绑定到同一个AsynchronousChannelGroup
            //CompletionHandler 用于处理程序完成的结果
            server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
                //设置缓冲区大小为1024字节
                final ByteBuffer buffer = ByteBuffer.allocateDirect(1024);

                @Override
                public void completed(AsynchronousSocketChannel result, Object attachment) {
                    System.out.println("I/O操作成功,开始获取数据");
                    try {
                        //clear清空缓冲区。
                        buffer.clear();
                        result.read(buffer).get();
                        // 用于buffer缓存对象内容填写后,转为读模式。(写进buffer后再flip(),可以读出buffer中的数据)
                        //四个关键的概念,position,limit,mark,capacity
                        //中文就叫位置,限制,标记,容量,他们的关系0<=mark<=position<=limit<capacity
                        //底层操作实际上是操作的数组
                        //capacity可以理解为数组的大小,position就是读取或写入时的下标,limit就是执行当前读或者写的最大下标
                        //还有一个mark,可以理解为一个备份点。使用reset()方法,就可以回到这个点
                        buffer.flip();
                        result.write(buffer);
                        buffer.flip();
                    } catch (Exception e) {
                        System.out.println(e.toString());
                    } finally {
                        try {
                            result.close();
                            server.accept(null, this);
                        } catch (Exception e) {
                            System.out.println(e.toString());
                        }
                    }
                    System.out.println("操作完成");
                }

                @Override
                public void failed(Throwable exc, Object attachment) {
                    System.out.println("I/O操作失败:" + exc);
                }
            });
            try {
                Thread.sleep(Integer.MAX_VALUE);
            } catch (InterruptedException ex) {
                System.out.println(ex);
            }
        } catch (IOException e) {
            System.out.println(e);
        }
    }

    public static void main(String[] args) {
        int port = 8000;
        new AIOServer(port);
    }
}

运行代码后,我们会发现不管是客户端还是服务端,其处理接收机消息的了逻辑都是一部操作。

参考

《Netty 4核心原理与手写RPC框架实现》 谭勇德(TOM)著

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值