Netty入门(三) --- Netty核心组件,Netty群聊系统

本文详细介绍了Netty的核心组件,包括Bootstrap、ServerBootstrap、Future、Channel、Selector、ChannelHandler、Pipeline、ChannelHandlerContext、ChannelOption、EventLoopGroup和NioEventLoopGroup以及Unpooled类。此外,还阐述了如何利用这些组件构建Netty的群聊系统,包括服务器端和客户端的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


往期

五、Netty核心组件

5.1 Bootstrap、ServerBootstrap

Bootstrap 意思是引导,一个 Netty 应用通常由一个 Bootstrap 开始,主要作用是配置整个 Netty 程序,串联各个组件

  • Bootstrap:客户端启动引导类
  • ServerBootstrap:服务器端启动引导类

常用方法:

public ServerBootstrap group(EventLoopGroup parentGroup, EventLoopGroup childGroup)//该方法用于服务器端,用来设置两个 EventLoop
public B group(EventLoopGroup group)//该方法用于客户端,用来设置一个 EventLoop
public B channel(Class<? extends C> channelClass)//该方法用来设置一个服务器端的通道实现
public <T> B option(ChannelOption<T> option, T value)//用来给 ServerChannel 添加配置
public <T> ServerBootstrap childOption(ChannelOption<T> childOption, T value)//用来给接收到的通道添加配置
public ServerBootstrap childHandler(ChannelHandler childHandler)//该方法用来设置业务处理类(自定义的 handler)
public ChannelFuture bind(int inetPort)//该方法用于服务器端,用来设置占用的端口号
public ChannelFuture connect(String inetHost, int inetPort)//该方法用于客户端,用来连接服务器

5.2 Future、ChannelFuture

Netty 中所有的IO操作都是异步的,不能立刻得知消息是否被正确处理,但是可以过一会等它执行完成或者直接注册一个监听。

具体实现就是Future和ChannelFuture

他们可以注册一个监听,当操作执行成功或失败时监听会自动触发注册的监听事件

常用方法:

Channel channel()//返回当前正在进行 IO 操作的通道 
ChannelFuture sync()//同步,阻塞等待Future完成从而获得其返回值

5.3 Channel

  • Netty 网络通信的组件,能够用于执行网络 I/O 操作
  • 通过Channel 可获得当前网络连接的通道的状态,获得网络连接的配置参数(例如接收缓冲区大小)
  • Channel 提供 异步的网络 I/O 操作 (如建立连接,读写,绑定端口),异步调用意味着任何 I/O 调用都将立即返回,并且不保证在调用结束时所请求的 I/O 操作已完成
  • 调用立即返回一个 ChannelFuture 实例,通过注册监听器到 ChannelFuture 上,可以在 I/O 操作成功、失败或取消时回调通知调用方
  • 不同协议、不同的阻塞类型的连接都有不同的 Channel 类型与之对应,常用的 Channel 类型如下:
    • NioSocketChannel,异步的客户端 TCP Socket 连接。
    • NioServerSocketChannel,异步的服务器端 TCP Socket 连接。
    • NioDatagramChannel,异步的 UDP 连接。
    • NioSctpChannel,异步的客户端 Sctp 连接。
    • NioSctpServerChannel,异步的 Sctp 服务器端连接,这些通道涵盖了 UDP 和 TCP 网络 IO 以及文件 IO。

5.4 Selector

  • Netty 基于 Selector 对象实现 I/O 多路复用 ,通过 Selector 一个线程可以监听多个连接的 Channel 事件。
  • 当向一个Selector注册Channel后,在NIOEventLoop中不断轮询select,查看这些Channel是否有就绪的IO事件(例如可读,可写,网络连接 完成等),这样程序就可以很简单地使用一个线程高效地管理多个 Channel

5.5 ChannelHandler

  • ChannelHandler 是一个接口,处理 I/O 事件或拦截 I/O 操作,并将其转发到其 ChannelPipeline 业务处理链 中的下一个处理程序

  • ChannelHandler 及其实现类一览图

    image-20220123143216648

  • 处理器

    • ChannelInboundHandler 用于处理入站 I/O 事件。
    • ChannelOutboundHandler 用于处理出站 I/O 操作。
  • 适配器

    • ChannelInboundHandlerAdapter 用于处理入站 I/O 事件。
    • ChannelOutboundHandlerAdapter 用于处理出站 I/O 操作。
    • ChannelDuplexHandler 用于处理入站和出站事件。

我们经常需要自定义一 个 Handler 类去继承 ChannelInboundHandlerAdapter,然后通过重写 相应方法实现业务逻辑

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);
    }
    
}

5.6 Pipeline 和 ChannelPipeline

之前架构图的细化:Channel和ChannelPipeline关系图

image-20220123145023525

  • 一个 Channel 包含了一个 ChannelPipeline,而 ChannelPipeline 中又维护了一个由ChannelHandlerContext 组成的双向链表,并且每个 ChannelHandlerContext 中又关联着一个 ChannelHandler
  • 入站事件和出站事件在一个双向链表中,入站事件会从链表 head 往后传递到最后一个入站的 handler, 出站事件会从链表 tail 往前传递到最前一个出站的 handler,两种类型的 handler 互不干扰

  • ChannelPipeline 是一个 Handler 的集合,它负责处理和拦截 inbound 或者 outbound 的事件和操作,相当于一个贯穿 Netty 的链。(ChannelPipeline 是保存 ChannelHandler 的 List,用于处理或拦截 Channel 的入站 事件和出站操作
  • ChannelPipeline 实现了一种高级形式的拦截过滤器模式,使用户可以完全控制事件的处理方式,以及 Channel 中各个的 ChannelHandler 如何进行交互

image-20220123145753394

如图:debug发现pipeline是双向链表,依次把HttpServerInitializer,HttpServerCodec,HttpServerHandler放进链表中

常用方法:

ChannelPipeline addFirst(ChannelHandler... handlers)//把一个业务处理类(handler)添加到链中的第一个位置
ChannelPipeline addLast(ChannelHandler... handlers)//把一个业务处理类(handler)添加到链中的最后一个位置

5.7 ChannelHandlerContext

保存 Channel 相关的所有上下文信息,同时关联一个 ChannelHandler 对象

即ChannelHandlerContext中包含一个具体的事件处理器 ChannelHandler ,同时ChannelHandlerContext 中也绑定了对应的 pipeline 和 Channel 的信息,方便对ChannelHandler进行调用

image-20220123153035210

常用方法:

ChannelFuture close()//关闭通道
ChannelOutboundInvoker flush()//刷新
ChannelFuture writeAndFlush(Object msg) //将数据写到 ChannelPipeline 中并刷新缓冲区

5.8 ChannelOption

Netty 在创建 Channel 实例后,一般都需要设置 ChannelOption 参数。ChannelOption 参数如下:

image-20220123153443573

  • ChannelOption.SO_BACKLOG:对应 TCP/IP 协议 listen 函数中的 backlog 参数,用来初始化服务器可连接队列大小。服务端处理客户端连接请求是顺序处理的,所以同一时间只能处理一个客户端连接。多个客户端来的时候,服务端将不能处理的客户端连接请求放在队列中等待处理,backlog 参数指定了队列的大小。
  • ChannelOption.SO_KEEPALIVE:一直保持连接活动状态

5.9 EventLoopGroup和NioEventLoopGroup

  • EventLoopGroup 是一组 EventLoop 的抽象,Netty 为了更好的利用多核 CPU 资源, 一般会有多个 EventLoop 同时工作,每个 EventLoop 维护着一个 Selector 实例。
  • EventLoopGroup 提供 next 接口,可以从组里面按照一定规则获取其中一个 EventLoop来处理任务。在 Netty 服务器端编程中,我们一般都需要提供两个 EventLoopGroup,例如:BossEventLoopGroup 和 WorkerEventLoopGroup。
  • 通常一个服务端口即一个 ServerSocketChannel对应一个Selector 和一个EventLoop 线程。
  • BossEventLoop 负责接收客户端的连接并将 SocketChannel 交给 WorkerEventLoopGroup 来进行 IO 处理

image-20220123153734399

常用方法

public NioEventLoopGroup()//构造方法
public Future<?> shutdownGracefully()//断开连接,关闭线程

5.10 Unpooled类

Netty 提供一个专门用来操作缓冲区(即Netty的数据容器)的工具类

//通过给定的数据和字符编码返回一个 ByteBuf 对象(类似于 NIO 中的 ByteBuffer 但有区别)
public static ByteBuf copiedBuffer(CharSequence string, Charset charset)

ByteBuf对象包含一个数组 arr 是一个byte[10],和NIO中的buffer类似,但是不需要读写切换

  • readIndex:读指针,readByte读方法会从读指针开始读到writerrIndex为止
  • writerIndex:写指针,writeByte方法往buffer写入数据时该指针递增
  • capactiy:容量,最大可写多少

image-20220123163529476


demo

public class NettyBufDemo {
    public static void main(String[] args) {
        //创建一个ByteBuf,该对象包含一个数组 arr 是一个byte[10]
        //netty的buffer中不需要 flip反转
        ByteBuf byteBuf = Unpooled.buffer(10);
        for (int i = 0; i < 10; i++) {
            byteBuf.writeByte(i);
        }

        System.out.println("capacity="+byteBuf.capacity());

        //getByte readIndex不会移动
        System.out.println("---getByte---");
        for (int i = 0; i < byteBuf.capacity(); i++) {
            System.out.println(byteBuf.getByte(i));
        }

        //readByte readIndex会移动
        System.out.println("---readByte---");
        for (int i = 0; i < byteBuf.capacity(); i++) {
            System.out.println(byteBuf.readByte());
        }

    }
}
public class NettyBufDemo02 {
    public static void main(String[] args) {
        ByteBuf byteBuf = Unpooled.copiedBuffer("hello,world", CharsetUtil.UTF_8);
        if (byteBuf.hasArray()){
            byte[] array = byteBuf.array();
            System.out.println(new String(array,CharsetUtil.UTF_8));
            int len = byteBuf.readableBytes();  // 可读的字节数
            System.out.println(len);

            System.out.println(byteBuf.arrayOffset());//偏移
            System.out.println(byteBuf.readerIndex());//读指针
            System.out.println(byteBuf.writerIndex());//写指针
            System.out.println(byteBuf.capacity());//容量


            //按范围读
            System.out.println(byteBuf.getCharSequence(0, 4, CharsetUtil.UTF_8));//从0开始读4个
            System.out.println(byteBuf.getCharSequence(4, 6, CharsetUtil.UTF_8));//从4开始读6个
        }
    }
}

六、Netty群聊系统

6.1 服务器端

GroupChatServer

public class GroupChatServer {
    private int port;

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

    //编写一个run处理客户端请求
    public void run(){
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,128)
                    .childOption(ChannelOption.SO_KEEPALIVE,true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //拿到管道
                            ChannelPipeline pipeline = ch.pipeline();
                            //管道添加解码器
                            pipeline.addLast("Decoder",new StringDecoder());
                            //管道添加编码器
                            pipeline.addLast("Encoder",new StringEncoder());
                            //加入自定义的Handler
                            pipeline.addLast(new GroupChatServerHandler());
                        }
                    });
            System.out.println("Server ok");
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new GroupChatServer(7000).run();
    }
}

GroupChatServerHandler

public class GroupChatServerHandler extends SimpleChannelInboundHandler<String> {

    //定义一个Channel组管理所有channel
    //GlobalEventExecutor 是一个全局事件执行器,单例模式,用INSTANCE获取
    private static final ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //handlerAdded 表示连接建立,一旦连接,第一个被执行
    //将当前连接的Channel加入 ChannelGroup 中进行管理
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        //将该客户聊天信息 推送到其他在线的客户端
        //ChannelGroup中的writeAndFlush会自动将所有的channel进行遍历
        channelGroup.writeAndFlush("[客户端]"+channel.remoteAddress()+"加入聊天---"+sdf.format(new Date())+"\n");
        channelGroup.add(channel);
    }

    //Channel活动状态,可以提醒服务器 xxx 上线
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress()+"上线了~"+sdf.format(new Date()));
    }

    //Channel非活动状态,可以提醒服务器 xxx 离开了,管道还在但是离开了
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress()+"离开了~"+sdf.format(new Date()));
    }

    //断开连接,管道不在了移除了
    //handlerRemoved结束后会导致当前channel移除,不用手动从channelGroup删除
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush("[客户端]"+channel.remoteAddress()+"下线了---"+sdf.format(new Date())+"\n");
        System.out.println("channelGroup中减少一个channel");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        StringBuffer stringBuffer = new StringBuffer(msg);
        stringBuffer.append("---时间:").append(sdf.format(new Date()));

        //获取当前channel
        Channel channel = ctx.channel();
        //这时遍历channelGroup,根据不同情况回送不同消息
        channelGroup.forEach(ch -> {
            if (ch!=channel){//不是当前的channel,转发消息
                ch.writeAndFlush("[客户]"+channel.remoteAddress()+" 发送消息:"+stringBuffer.toString());
            }else {//回显自己的消息给自己
                ch.writeAndFlush("[自己]发送到群聊:"+stringBuffer.toString());
            }
        });
    }

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

6.2 客户端

GroupChatClient

public class GroupChatClient {
    private int port;
    private String host;

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

    public void run(){
        EventLoopGroup eventExecutors = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventExecutors)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast("Decoder",new StringDecoder());
                            pipeline.addLast("Encoder",new StringEncoder());
                            pipeline.addLast(new GroupChatClientHandler());
                        }
                    });
            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            //拿到channel,发送消息
            Channel channel = channelFuture.channel();
            System.out.println("---"+ channel.localAddress()+"ready---");
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()){
                String msg = scanner.nextLine();
                channel.writeAndFlush(msg);
            }
            channel.closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            eventExecutors.shutdownGracefully();
        }

    }

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

GroupChatClientHandler

public class GroupChatClientHandler extends SimpleChannelInboundHandler<String> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println(msg.trim());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("服务器出错了");
    }
}

运行截图:

开启服务器,陆续开启三个客户端

image-20220123175817795

每个客户端发送自己是谁:

image-20220123175959382

客户端陆续离线

image-20220123180044820

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值