Netty(中)

1、Netty模型

1.1、简单原理示意图

1.2、示意图解释

1.3、原理示意图进阶版

1.4、原理示意图最终版

1.5、示意图解释

2、Netty快速入门案例 - TCP服务

2.1、NettyServer

/**
 * @author wzcstart
 * @date 2021/6/23 - 23:51
 */
public class NettyServer {
    public static void main(String[] args) throws Exception{
        //创建BossGroup 和 WorkerGroup
        //说明
        //1、 创建两个线程组 boosGroup 和workerGroup
        //2、 bossGroup 只是处理连接请求,真正的和客户端业务处理,会交给workerGroup完成
        //3、 两个都是无限循环
        //4、 boosGroup 和 workerGroup 默认有 内核*2 个NioEventLoop
        //      NettyRuntime.availableProcessors() * 2
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {


            //创建服务端的启动对象,配置参数
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)//设置两个线程组
                    .channel(NioServerSocketChannel.class) //使用NioServerSocketChannel 作为服务器的通道实现
                    .option(ChannelOption.SO_BACKLOG, 128) //设置线程队列连接的个数
                    .childOption(ChannelOption.SO_KEEPALIVE, true) //设置保持活动连接状态
                    .childHandler(new ChannelInitializer<SocketChannel>() { //创建一个通道初始化对象
                        //给pipeline 设置处理器
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new NettyServerHandler());
                        }
                    }); // 给我们的workerGroup 的 EventLoop 对应的管道设置处理器

            System.out.println("......服务端 is ready");

            //绑定一个端口并同步返回,生成了一个 ChannelFuture 对象
            //启动服务器(并绑定端口)
            ChannelFuture cf = bootstrap.bind(6668).sync();

            //对关闭通道进行监听
            cf.channel().closeFuture().sync();
        }finally {
            //关闭
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

2.2、NettyServerHandler

/**
 * @author wzcstart
 * @date 2021/6/24 - 22:19
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * 读取数据
     * @param ctx 通道处理器上下文,封装了很多对象
     * @param msg 客户端发送的消息
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        System.out.println("当前读取的线程:"+Thread.currentThread().getName());
        System.out.println("server ctx = "+ctx);

        Channel channel = ctx.channel();
        ChannelPipeline pipeline = ctx.pipeline();

        //将 msg 转换为ByteBuf
        //ByteBuf 是netty包下的
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("服务器发送的消息是:"+buf.toString(CharsetUtil.UTF_8));
        System.out.println("客户端地址:"+ channel.remoteAddress());

    }

    /**
     * 读取数据完毕
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

        //writeAndFlush 是 write + flush
        //将数据写入到缓存,并刷新
        //一般讲,我们对这个发送的数据进行编码
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端~", CharsetUtil.UTF_8));

    }

    // 处理异常,一般关闭通道
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}

2.3、NettyClient

/**
 * @author wzcstart
 * @date 2021/6/24 - 22:43
 */
public class NettyClient {
    public static void main(String[] args) throws Exception {

        //客户端需要一个循环事件组
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            //客户端启动设置
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group) // 指定循环事件组
                    .channel(NioSocketChannel.class)// 指定通道
                    .handler(new ChannelInitializer<SocketChannel>() { //添加处理器
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new NettyClientHandler()); //加入自己的处理器
                        }
                    });

            System.out.println("客户端 is ok...");

            //启动客户端去连接服务器端
            //关于ChannelFuture 要分析,涉及 netty 异步模型
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 6668).sync();
            //异步监听关闭连接
            channelFuture.channel().closeFuture().sync();
        } finally {
            //关闭
            group.shutdownGracefully();
        }

    }
}

2.4、NettyClientHandler

/**
 * @author wzcstart
 * @date 2021/6/24 - 22:59
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    //当通道连接成功
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("client ctx ="+ctx);
        //给服务端发送消息
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello,服务端", CharsetUtil.UTF_8));
    }

    //监听到服务端发送来的消息
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("服务端发送的消息是:"+buf.toString(CharsetUtil.UTF_8));
        System.out.println("服务端地址:"+ctx.channel().remoteAddress());

    }

    //处理异常

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}

3、Task三种经典使用场景

3.1、说明

3.2、代码演示

    /**
     * 读取数据
     * @param ctx 通道处理器上下文,封装了很多对象
     * @param msg 客户端发送的消息
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {


        //用户自定义任务 - taskQueue
        ctx.channel().eventLoop().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println(Thread.currentThread().getName()+"执行任务一");
                    TimeUnit.SECONDS.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                ctx.channel().writeAndFlush(Unpooled.copiedBuffer("任务一",CharsetUtil.UTF_8));
            }
        });


        ctx.channel().eventLoop().execute(()->{
                try {
                    System.out.println(Thread.currentThread().getName()+"执行任务二");
                    TimeUnit.SECONDS.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                ctx.channel().writeAndFlush(Unpooled.copiedBuffer("任务二",CharsetUtil.UTF_8));
            });


        //用户自定义定时任务 - scheduleTaskQueue
        System.out.println("go on ...");

        /*System.out.println("当前读取的线程:"+Thread.currentThread().getName());
        System.out.println("server ctx = "+ctx);

        Channel channel = ctx.channel();
        ChannelPipeline pipeline = ctx.pipeline();

        //将 msg 转换为ByteBuf
        //ByteBuf 是netty包下的
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("服务器发送的消息是:"+buf.toString(CharsetUtil.UTF_8));
        System.out.println("客户端地址:"+ channel.remoteAddress());*/

    }

4、代码套路方案再说明

5、异步模型

5.1、基本介绍

5.2、Future说明

5.3、工作原理示意图

5.4、Future-Listener

ChannelFuture cf = bootstrap.bind(6668).sync();

            cf.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (cf.isSuccess()){
                        System.out.println("绑定成功");
                    }else{
                        System.out.println("绑定失败");
                    }
                }
            });

6、Netty核心组件

6.1、Bootstrap、ServerBootstrap - 引导器

6.2、Future、ChannelFuture

6.3、Channel

6.4、Selector

6.5、ChannelHandler及其实现类

public class ChannelInboundHandlerAdapter extends ChannelHandlerAdapter implements ChannelInboundHandler {
    public ChannelInboundHandlerAdapter() { }
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        ctx.fireChannelRegistered();
    }
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        ctx.fireChannelUnregistered();
    }
    //通道就绪事件
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.fireChannelActive();
    }
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        ctx.fireChannelInactive();
    }
    //通道读取数据事件
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ctx.fireChannelRead(msg);
    }
    //数据读取完毕事件
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.fireChannelReadComplete();
    }
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        ctx.fireUserEventTriggered(evt);
    }
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
        ctx.fireChannelWritabilityChanged();
    }
    //通道发生异常事件
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.fireExceptionCaught(cause);
    }
}

6.6、ChannelPipeline和ChannelPipeline

6.7、ChannelHandlerContext

6.8、ChannelOption

6.9、EventLoopGroup和其实现类NioEventLoopGroup

6.10、Unpooled

6.10.1、案例一

package com.guiguixia.netty.buf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

import java.util.LinkedList;

/**
 * @author wzcstart
 * @date 2021/6/27 - 21:51
 */
public class NettyByteBuf01 {
    public static void main(String[] args){
        //1、 构建一个ByteBuf
        //2、 ByteBuf 不用向 ByteBuffer 一样使用 flip()方法反转,
        //    因为 ByteBuf 内部维护了 writerIndex 和 readIndex
        //3、 ByteBuf 通过 0 -- readIndex -- WriterIndex -- capacity 分成三段
        //          0 -- readIndex 已读取的范围
        //          readIndex -- WriterIndex 可读的范围
        //          WriterIndex -- capacity 可写的范围
        ByteBuf buf = Unpooled.buffer(10);

        for (int i = 0; i < 10; i++) {
            //每次写一个,writerIndex 向后移一位
            buf.writeByte(i);
        }

        for (int i = 0; i < buf.capacity(); i++) {
            //此处没有使用 buf.readByte() 如果使用则 readIndex 向后移一位
            System.out.println(buf.getByte(i));;
        }

        System.out.println("运行结束了!");

        LinkedList<Object> queue = new LinkedList<>();
        Object o = queue.removeFirst();
    }
}

6.10.2、案例二

package com.guiguixia.netty.buf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

import java.nio.charset.Charset;

/**
 * @author wzcstart
 * @date 2021/6/27 - 23:44
 */
public class NettyByteBuf02 {
    public static void main(String[] args){
        ByteBuf byteBuf = Unpooled.copiedBuffer("hello,world!", Charset.forName("utf-8"));

        if (byteBuf.hasArray()){

            System.out.println("array="+byteBuf.array());//hello,world!
            System.out.println("capacity="+byteBuf.capacity());//32
            System.out.println("readIndex="+byteBuf.readerIndex());//0
            System.out.println("writerIndex="+byteBuf.readerIndex());//12
            System.out.println("arrayOffset"+byteBuf.arrayOffset());//0
            int len = byteBuf.readableBytes();
            System.out.println("len="+len);//12

            for (int i = 0; i < len; i++) {
                //不改变 readableBytes - readByte()方法会改变
                System.out.println((char) byteBuf.getByte(i));
            }

            System.out.println("读取index=0,len=4,Charset=utf-8 => "+
                    byteBuf.getCharSequence(0, 4, Charset.forName("utf-8") ));
            System.out.println("读取index=4,len=6,Charset=utf-8 => "+
                    byteBuf.getCharSequence(4, 6, Charset.forName("utf-8") ));

            System.out.println("is ok ...");
        }
    }
}

6.11、Netty群聊系统

6.11.1、GroupChatServer

/**
 * @author wzcstart
 * @date 2021/6/28 - 22:26
 */
public class GroupChatServer {

    private int port;

    public GroupChatServer(int port) {
        this.port = port;
    }

    private void run() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup(8);
        try {
            //构建引导器
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childOption(ChannelOption.SO_BACKLOG, 128)//当线程已达到最大连接,可存放的最大已建立TCP三次握手的数量
                    .childOption(ChannelOption.SO_KEEPALIVE, true)//开启心跳检测活跃
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //获取管道
                            ChannelPipeline pipeline = ch.pipeline();
                            //加入字符解码器
                            pipeline.addLast(new StringDecoder());
                            //加入字符编码器
                            pipeline.addLast(new StringEncoder());
                            //加入自己的处理器
                            pipeline.addLast(new GroupChatServerChannelHandler());
                        }
                    });

            ChannelFuture channelFuture = bootstrap.bind(port).sync();
            System.out.println("server is ok ...");
            //监听关闭事件
            channelFuture.channel().closeFuture().sync();
        }finally {
            //关闭资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception{

        new GroupChatServer(7000).run();

    }
}

6.11.2、GroupChatServerChannelHandler

/**
 * @author wzcstart
 * @date 2021/6/28 - 22:39
 */
public class GroupChatServerChannelHandler extends SimpleChannelInboundHandler<String> {

    //统一存放所有的channel通道
    //GlobalEventExecutor.INSTANCE全局事件处理器单实例
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    //设置时间格式
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:MM:ss");

    //处理私聊
    private static Map<String, Channel> cache = new HashMap<String, Channel>();

    //正则
    private static Pattern pattern = Pattern.compile(".*-->(.*)}");

    //只要连接一建立最先执行的方法
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {

        Channel channel = ctx.channel();
        //再当前channel 加入到channelGroup之前先将channel上线转发给所有channel
        //writeAndFlush 方法会遍历发给channelGroup里所有的channel
        channelGroup.writeAndFlush("[客户端]"+channel.remoteAddress()+" "+sdf.format(new Date())+" 加入聊天\n");
        //将当前channel加入到channelGroup
        channelGroup.add(channel);

    }

    //建立连接 - 活跃连接
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //将 port 加入到 cache
        String port = ctx.channel().remoteAddress().toString().split(":")[1];
        cache.put(port,ctx.channel());
        System.out.println(ctx.channel().remoteAddress()+" 上线了~");
    }

    //非活跃连接
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress()+" 离线了~");
    }

    //断开连接 - 自动从channelGroup中移除channel
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        //将 port 移除 cache
        String port = ctx.channel().remoteAddress().toString().split(":")[1];
        cache.remove(port);

        Channel channel = ctx.channel();

        channelGroup.writeAndFlush("[客户端]"+channel.remoteAddress()+" 离开了\n");
        System.out.println("channelGroup size = "+channelGroup.size());
    }

    //读数据
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        if (msg.contains("-->")){
            String[] res = msg.split("-->");
            String group = res[1];
            String[] split = group.split(",");
            for (String s : split) {
                Channel channel = cache.get(s);
                channel.writeAndFlush(ctx.channel().remoteAddress()+"-->"+res[0]);
            }
            return;
        }

        //获取到当前channel
        Channel channel = ctx.channel();

        channelGroup.forEach(ch->{
            if (ch!=channel){
                ch.writeAndFlush(sdf.format(new Date())+"[客户:"+channel.remoteAddress()+"] "+msg);
            }else {
                channel.writeAndFlush("[发送完成] "+msg);
            }
        });
    }

    //捕捉到异常 - 关闭通道
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //关闭通道
        ctx.channel().close();
    }
}

6.11.3、GroupChatClient

/**
 * @author wzcstart
 * @date 2021/6/29 - 14:25
 */
public class GroupChatClient {

    //连接的主机ip
    private String host;
    //端口
    private int port;

    public GroupChatClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void run() throws Exception{
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //得到pipeline
                            ChannelPipeline pipeline = ch.pipeline();
                            //加入编解码器
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new StringEncoder());
                            pipeline.addLast(new GroupChatClientChannelHandler());
                        }
                    });

            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            //获取到channel
            Channel channel = channelFuture.channel();
            System.out.println("[客户端:"+channel.localAddress()+"]准备好了");
            Scanner scanner = new Scanner(System.in);

            while (scanner.hasNextLine()){
                String msg = scanner.nextLine();
                //通过channel发送信息
                channel.writeAndFlush(msg);
            }

        }finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception{
        new GroupChatClient("127.0.0.1", 7000).run();
    }
}

6.11.4、GroupChatClientChannelHandler

/**
 * @author wzcstart
 * @date 2021/6/29 - 14:48
 */
public class GroupChatClientChannelHandler extends SimpleChannelInboundHandler<String> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println(msg);
    }
}

6.11.5、效果展示

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值