Netty学习系列(3)

185 阅读10分钟

六、Netty核心模块组件

6.1 类分析

6.1.1 Bootstrap、ServerBootstrap

  1. Bootstrap是引导类,一个 Netty 应用通常由一个 Bootstrap 开始,主要作用是配置整个 Netty 程序,串联各个组件,NettyBootstrap 类是客户端程序的启动引导类,ServerBootstrap 是服务端启动引导类。

  2. 常见方法如下图

    • BootStrap

      image-20210722092732806

    • ServerBootStrap

      image-20210722092927045

    • 父类AbstractBootstrap

      image-20210722093319561

6.1.2 Future、ChannelFuture

Netty 中所有的 IO 操作都是异步的,不能立刻得知消息是否被正确处理。但是可以过一会等它执行完成或者直接注册一个监听,具体的实现就是通过 FutureChannelFuture,他们可以注册一个监听,当操作执行成功或失败时监听会自动触发注册的监听事件

image-20210722093635342

6.1.3 Channel

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

6.1.4 Selector

  1. Netty 基于 Selector 对象实现 I/O 多路复用,通过 Selector 一个线程可以监听多个连接的 Channel 事件。
  2. 当向一个 Selector 中注册 Channel 后,Selector 内部的机制就可以自动轮询(Select)这些注册的 Channel 是否有已就绪的 I/O 事件(例如可读,可写,网络连接完成等),这样程序就可以很简单地使用一个线程高效地管理多个 Channel

6.1.5 ChannelHandler及其实现类

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

  2. ChannelHandler 本身并没有提供很多方法,因为这个接口有许多的方法需要实现,方便使用期间,可以继承它的子类

  3. ChannelHandler 及其实现类如下图

    image-20210722100334058

  4. 根据第五章Netty模型-编码实例中,我们需要自定义一个Handler集成ChannelInboundHandlerAdapter,然后通过重写方法实现具体业务逻辑,常用的重写方法如下图

    image-20210722100741474

6.1.6 Pipeline和ChannelPipeline(重点)

ChannelPipeline 是一个重点:

  1. ChannelPipeline 是一个 Handler 的集合,它负责处理和拦截 inbound 或者 outbound 的事件和操作,相当于一个贯穿 Netty 的链。(也可以这样理解:ChannelPipeline 是保存 ChannelHandlerList,用于处理或拦截 Channel 的入栈事件和出栈操作)
  2. ChannelPipeline 实现了一种高级形式的拦截过滤器模式(类似责任链模式),使用户可以完全控制事件的处理方式,以及 Channel 中各个的 ChannelHandler 如何相互交互
  3. Netty 中每个 Channel 都有且仅有一个 ChannelPipeline 与之对应,它们的组成关系如下图

image-20210722101802692

  1. 最常用的方法如下图

    image-20210722102024007

6.1.7 ChannelHandlerContext

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

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

  3. 常用方法如下图

    image-20210722102540346

6.1.8 ChannelOption

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

  2. ChannelOption 常用参数如下图

    image-20210722103002146

6.1.9 EventLoopGroup及其实现类NioEventLoopGroup

  1. EventLoopGroup 是一组 EventLoop 的抽象,Netty 为了更好的利用多核 CPU 资源,一般会有多个 EventLoop 同时工作,每个 EventLoop 维护着一个 Selector 实例。

  2. EventLoopGroup 提供 next 接口,可以从组里面按照一定规则获取其中一个 EventLoop 来处理任务。在 Netty 服务器端编程中,我们一般都需要提供两个 EventLoopGroup,例如:BossEventLoopGroupWorkerEventLoopGroup

  3. 通常一个服务端口即一个 ServerSocketChannel 对应一个 Selector 和一个 EventLoop 线程。BossEventLoop 负责接收客户端的连接并将 SocketChannel 交给 WorkerEventLoopGroup 来进行 IO 处理,如下图所示

    image-20210722104045374

    • 通常情况下,BossEventLoopGroup是一个单线程的EventLoop(处理连接单线程就够了),EventLoop维护一个注册了ServerSocketChannelSelector实例,BossEventLoop不断轮询Selector将连接事件分离出来。
    • BossEventLoopGroup收到OP_ACCEPT事件,然后将收到的SocketChannel交给WorkerEventLoopGroupWorkerEventLoopGroup通过next选择其中一个EventLoopSocketChannel注册到其维护的Selector,并对其后续IO事件进行处理
  4. 常用方法如下图

    image-20210722104658391

6.1.10 Unpooled

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

  2. 常用方法如下图(写入数据,返回ByteBuf对象,类似NIO中的ByteBuffer

    image-20210722105710792

  3. 编码举例说明

    package com.nic.netty.buf;
    
    import io.netty.buffer.ByteBuf;
    import io.netty.buffer.Unpooled;
    import io.netty.util.CharsetUtil;
    
    /**
     * Description:
     * ByteBuf举例说明测试
     *
     * @author james
     * @date 2021/7/22 10:59
     */
    public class NettyByteBufTest
    {
        public static void main(String[] args) {
            //创建一个ByteBuf
            //说明
            //1. 创建 对象,该对象包含一个数组arr , 是一个byte[10]
            //2. 在netty 的buffer中,不需要使用flip 进行反转,底层维护了 readerindex 和 writerIndex
            //3. 通过 readerindex 和  writerIndex 和  capacity, 将buffer分成三个区域
            // 0---readerindex              已经读取的区域
            // readerindex---writerIndex , 可读的区域
            // writerIndex -- capacity,     可写的区域
    
            ByteBuf buffer = Unpooled.buffer(10);
    
            for (int i = 0; i < 10; i++) {
                buffer.writeByte(i);
            }
    
            System.out.println("capacity = " + buffer.capacity());
    
            for (int i = 0; i < buffer.capacity(); i++) {
                //两者输出相同
                System.out.println(buffer.getByte(i));// 0 1 2 3 4 5 6 7 8 9
                System.out.println(buffer.readByte());// 0 1 2 3 4 5 6 7 8 9
                System.out.println("-----------------");
            }
    
            System.out.println("=========================================");
            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));
    
                System.out.println("byteBuf = " + byteBuf);
    
                //偏移量
                System.out.println(byteBuf.arrayOffset());
                //当前读到的位置
                System.out.println(byteBuf.readerIndex());
                //当前可写的位置
                System.out.println(byteBuf.writerIndex());
                //buf的容量
                System.out.println(byteBuf.capacity());
    
                //执行readByte之后,readerIndex会+1
                //            System.out.println(byteBuf.readByte());
                //            System.out.println(byteBuf.readerIndex());
                System.out.println(byteBuf.getByte(0));
    
                //可读字节数
                //以上调用readByte()之后,可读字节数会-1
                System.out.println("len = " + byteBuf.readableBytes());
    
                for (int i = 0; i < byteBuf.readableBytes(); i++) {
                    System.out.println((char) byteBuf.getByte(i));
                }
    
                //自定义开头和长度读取buf中的内容
                System.out.println(byteBuf.getCharSequence(0, 4, CharsetUtil.UTF_8));
                System.out.println(byteBuf.getCharSequence(4, 8, CharsetUtil.UTF_8));
            }
        }
    }
    

6.2 编码实例(群聊系统)

实例要求:

注:功能与第三章4.3相同,只不过实现方式不同,这边通过Netty实现

  1. 编写一个 Netty 群聊系统,实现服务器端和客户端之间的数据简单通讯(非阻塞)
  2. 实现多人群聊
  3. 服务器端:可以监测用户上线,离线,并实现消息转发功能
  4. 客户端:通过 channel 可以无阻塞发送消息给其它所有用户,同时可以接受其它用户发送的消息(有服务器转发得到)

测试步骤:

  1. 启动Netty服务端

    image-20210722140610536

  2. 然后分别启动客户端(1)(2)(3)(4),服务端会分别看到4个客户端上线的消息,客户端也会分别收到其他客户端加入聊天的消息,由于客户端4最后加入,所以不会受到其他客户端加入聊天的消息

    image-20210722140749508

    image-20210722140948387

  3. 客户端1发送消息,其他客户端都收到了消息

    image-20210722141327076

代码如下:

  • 服务端

    package com.nic.netty.groupchat;
    
    import io.netty.bootstrap.ServerBootstrap;
    import io.netty.channel.ChannelFuture;
    import io.netty.channel.ChannelInitializer;
    import io.netty.channel.ChannelOption;
    import io.netty.channel.ChannelPipeline;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.channel.socket.nio.NioServerSocketChannel;
    import io.netty.handler.codec.string.StringDecoder;
    import io.netty.handler.codec.string.StringEncoder;
    
    /**
     * Description:
     * Netty群聊系统服务端
     *
     * @author james
     * @date 2021/7/22 11:21
     */
    public class GroupChatServer
    {
        private int port;
    
        public GroupChatServer(int port) {
            this.port = port;
        }
    
        public static void main(String[] args) {
            new GroupChatServer(7102).listen();
        }
    
        public void listen() {
            NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
            NioEventLoopGroup workerGroup = new NioEventLoopGroup(4);
    
            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())
                                        .addLast("encoder", new StringEncoder())
                                        .addLast(new GroupChatServerHandler());
                            }
                        });
                System.out.println("netty 服务器 is ready...");
                ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
                channelFuture.channel().closeFuture().sync();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            finally {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        }
    }
    
  • 服务端自定义handler

    package com.nic.netty.groupchat;
    
    import cn.hutool.core.date.DateUtil;
    import io.netty.channel.Channel;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.SimpleChannelInboundHandler;
    import io.netty.channel.group.ChannelGroup;
    import io.netty.channel.group.DefaultChannelGroup;
    import io.netty.util.concurrent.GlobalEventExecutor;
    
    /**
     * Description:
     * SimpleChannelInboundHandler和ChannelInboundHandlerAdapter区别:
     * SimpleChannelInboundHandler会负责释放指向保存该消息的ByteBuf的内存引用。
     * 而ChannelInboundHandlerAdapter在其时间节点上不会释放消息,而是将消息传递给下一个ChannelHandler处理。
     *
     * @author james
     * @date 2021/7/22 11:26
     */
    public class GroupChatServerHandler extends SimpleChannelInboundHandler<String>
    {
    
        //channel组,管理所有channel
        //GlobalEventExecutor.INSTANCE 全局时间执行器,单例
        private static final ChannelGroup CHANNEL_GROUP = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    
        //以下重写方法执行顺序
        // handlerAdd -> channelActive -> channelInactive -> handlerRemoved
        // 客户端 writeAndFlush之后,触发channelRead0
    
        /**
         * 连接建立就执行
         *
         * @param ctx
         * @throws Exception
         */
        @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
            Channel channel = ctx.channel();
            System.out.println("handlerAdd " + channel.remoteAddress());
            //将上线的客户推送给其他客户端
            //此方法会将group中所有的channel都写一遍
            CHANNEL_GROUP.writeAndFlush("[客户端] " + channel.remoteAddress() + " 加入聊天 " + DateUtil.now() + " \n");
            CHANNEL_GROUP.add(channel);
        }
    
        /**
         * 断开连接就执行
         *
         * @param ctx
         * @throws Exception
         */
        @Override
        public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
            Channel channel = ctx.channel();
            System.out.println("handlerRemoved " + channel.remoteAddress());
            CHANNEL_GROUP.writeAndFlush("[客户端] " + channel.remoteAddress() + " 退出聊天 " + DateUtil.now() + " \n");
            System.out.println("channelGroup size = " + CHANNEL_GROUP.size());
        }
    
        /**
         * 表示channel处于活动状态,与handlerAdded区分开
         * 先channelActive,然后handlerAdd
         *
         * @param ctx
         * @throws Exception
         */
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            System.out.println("channelActive " + ctx.channel().remoteAddress());
            System.out.println(ctx.channel().remoteAddress() + " 上线了 " + DateUtil.now());
        }
    
        /**
         * channel处于非活动状态,与handlerRemoved区分开
         *
         * @param ctx
         * @throws Exception
         */
        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            System.out.println("channelInactive " + ctx.channel().remoteAddress());
            System.out.println(ctx.channel().remoteAddress() + " 离线了 " + DateUtil.now());
        }
    
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
            Channel channel = ctx.channel();
            System.out.println("channelRead0 " + channel.remoteAddress());
            CHANNEL_GROUP.forEach(cg -> {
                //判断是否是当前channel,不是就转发消息
                if (cg != channel) {
                    cg.writeAndFlush("[客户端] " + channel.remoteAddress() + " 发送了消息 " + msg + " " + DateUtil.now() + "\n");
                }
                else {
                    cg.writeAndFlush("[自己] 发送了消息" + msg + " " + DateUtil.now());
                }
            });
        }
    
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            ctx.close();
        }
    }
    
  • 客户端

    package com.nic.netty.groupchat;
    
    import io.netty.bootstrap.Bootstrap;
    import io.netty.channel.Channel;
    import io.netty.channel.ChannelFuture;
    import io.netty.channel.ChannelInitializer;
    import io.netty.channel.ChannelPipeline;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.channel.socket.nio.NioSocketChannel;
    import io.netty.handler.codec.string.StringDecoder;
    import io.netty.handler.codec.string.StringEncoder;
    
    import java.util.Scanner;
    
    /**
     * Description:
     * Netty群聊系统客户端
     *
     * @author james
     * @date 2021/7/22 13:44
     */
    public class GroupChatClient
    {
        private String host;
        private int port;
    
        public GroupChatClient(String host, int port) {
            this.host = host;
            this.port = port;
        }
    
        public static void main(String[] args) {
            new GroupChatClient("127.0.0.1", 7102).run();
        }
    
        public void run() {
            NioEventLoopGroup 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 {
                                ChannelPipeline pipeline = ch.pipeline();
                                pipeline.addLast("decoder", new StringDecoder())
                                        .addLast("encoder", new StringEncoder())
                                        .addLast(new GroupChatClientHandler());
                            }
                        });
                ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
    
                Channel channel = channelFuture.channel();
                System.out.println("client channel address = " + channel.remoteAddress());
    
                Scanner scanner = new Scanner(System.in);
                while (scanner.hasNextLine()) {
                    String str = scanner.nextLine();
                    channel.writeAndFlush(str);
                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            finally {
                group.shutdownGracefully();
            }
        }
    }
    
  • 客户端自定义handler

    package com.nic.netty.groupchat;
    
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.SimpleChannelInboundHandler;
    
    /**
     * Description:
     *
     * @author james
     * @date 2021/7/22 13:49
     */
    public class GroupChatClientHandler extends SimpleChannelInboundHandler<String>
    {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
            System.out.println("client channelRead0 = " + msg.trim());
        }
    }
    

6.3 编码实例(心跳检测)

实例要求:

  1. 编写一个 Netty 心跳检测机制案例,当服务器超过 3 秒没有读时,就提示读空闲
  2. 当服务器超过 5 秒没有写操作时,就提示写空闲
  3. 实现当服务器超过 7 秒没有读或者写操作时,就提示读写空闲

测试步骤:

  1. 启动HeartBeatServer服务端

    image-20210722144708687

  2. 启动6.2群聊系统中的客户端(不需要专门写一个客户端,只是为了测试心跳),服务端3秒后、5秒后、7秒后分别会打印出空闲的信息

    读空闲每隔3秒打印一条消息,写空闲每隔5秒打印,读写空闲每隔7秒打印

    image-20210722145042786

代码如下:

  • 服务端

    package com.nic.netty.heartbeat;
    
    import io.netty.bootstrap.ServerBootstrap;
    import io.netty.channel.ChannelFuture;
    import io.netty.channel.ChannelInitializer;
    import io.netty.channel.ChannelPipeline;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.channel.socket.nio.NioServerSocketChannel;
    import io.netty.handler.logging.LogLevel;
    import io.netty.handler.logging.LoggingHandler;
    import io.netty.handler.timeout.IdleStateHandler;
    
    /**
     * Description:
     * Netty心跳检测服务
     *
     * @author james
     * @date 2021/7/22 14:20
     */
    public class HeartBeatServer
    {
        private int port;
    
        public HeartBeatServer(int port) {
            this.port = port;
        }
    
        public static void main(String[] args) {
            new HeartBeatServer(7102).listen();
        }
    
        public void listen() {
    
            NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
            NioEventLoopGroup workerGroup = new NioEventLoopGroup(4);
    
            try {
                ServerBootstrap serverBootstrap = new ServerBootstrap();
                serverBootstrap.group(bossGroup, workerGroup)
                        .channel(NioServerSocketChannel.class)
                        .handler(new LoggingHandler(LogLevel.INFO))
                        .childHandler(new ChannelInitializer<SocketChannel>()
                        {
                            @Override
                            protected void initChannel(SocketChannel ch) throws Exception {
                                ChannelPipeline pipeline = ch.pipeline();
    
                                //加入netty提供 IdleStateHandler
                                /**
                                 * 说明
                                 * 1. IdleStateHandler 是netty 提供的处理空闲状态的处理器
                                 * 2. long readerIdleTime : 表示多长时间没有读, 就会发送一个心跳检测包检测是否连接
                                 * 3. long writerIdleTime : 表示多长时间没有写, 就会发送一个心跳检测包检测是否连接
                                 * 4. long allIdleTime : 表示多长时间没有读写, 就会发送一个心跳检测包检测是否连接
                                 *
                                 * 当 IdleStateEvent 触发后 , 就会传递给管道 的下一个handler去处理
                                 * 通过调用(触发)下一个handler 的 userEventTiggered , 在该方法中去处理 IdleStateEvent(读空闲,写空闲,读写空闲)
                                 */
                                pipeline
                                        .addLast(new IdleStateHandler(3, 5, 7))
                                        .addLast(new HeartBeatServerHandler());
                            }
                        });
    
                ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
                channelFuture.channel().closeFuture().sync();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            finally {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
    
        }
    }
    
  • 服务端自定义handler

    package com.nic.netty.heartbeat;
    
    import cn.hutool.core.date.DateUtil;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.ChannelInboundHandlerAdapter;
    import io.netty.handler.timeout.IdleStateEvent;
    
    /**
     * Description:
     *
     * @author james
     * @date 2021/7/22 14:27
     */
    public class HeartBeatServerHandler extends ChannelInboundHandlerAdapter
    {
    
        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (evt instanceof IdleStateEvent) {
                System.out.println("userEventTriggered");
                IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
                String eventType = "";
                switch (idleStateEvent.state()) {
                    case READER_IDLE:
                        eventType = "读空闲";
                        break;
                    case WRITER_IDLE:
                        eventType = "写空闲";
                        break;
                    case ALL_IDLE:
                        eventType = "读写空闲";
                        break;
                    default:
                        break;
                }
                System.out.println(ctx.channel().remoteAddress() + " 超时 " + eventType + " 当前时间:" + DateUtil.now());
                System.out.println("服务器做处理。。。");
            }
        }
    }
    

6.4 编码实例(WebSocket实现长连接)

实例要求:

  1. Http 协议是无状态的,浏览器和服务器间的请求响应一次,下一次会重新创建连接。
  2. 要求:实现基于 WebSocket 的长连接的全双工的交互
  3. 改变 Http 协议多次请求的约束,实现长连接了,服务器可以发送消息给浏览器
  4. 客户端浏览器和服务器端会相互感知,比如服务器关闭了,浏览器会感知,同样浏览器关闭了,服务器会感知

测试步骤:

  1. 启动WebSocketServer服务端

    image-20210722152805053

  2. 访问index.html,会出现"连接开启了"

    image-20210722152834122

  3. 在发消息框中输入消息,点击发送,WebSocketServer控制台会出现浏览器发送的消息,内容框中会出现服务器回复的消息

    image-20210722153130172

    image-20210722153045718

代码如下:

  • 服务端

    package com.nic.netty.websocket;
    
    import io.netty.bootstrap.ServerBootstrap;
    import io.netty.channel.ChannelFuture;
    import io.netty.channel.ChannelInitializer;
    import io.netty.channel.ChannelPipeline;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.channel.socket.nio.NioServerSocketChannel;
    import io.netty.handler.codec.http.HttpObjectAggregator;
    import io.netty.handler.codec.http.HttpServerCodec;
    import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
    import io.netty.handler.logging.LogLevel;
    import io.netty.handler.logging.LoggingHandler;
    import io.netty.handler.stream.ChunkedWriteHandler;
    
    /**
     * Description:
     * WebSocket 实现长连接服务端
     *
     * @author james
     * @date 2021/7/22 14:54
     */
    public class WebSocketServer
    {
        private int port;
    
        public WebSocketServer(int port) {
            this.port = port;
        }
    
        public static void main(String[] args) {
            new WebSocketServer(7103).listen();
        }
    
        public void listen() {
    
            NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
            NioEventLoopGroup workerGroup = new NioEventLoopGroup();
    
            try {
                ServerBootstrap serverBootstrap = new ServerBootstrap();
                serverBootstrap.group(bossGroup, workerGroup)
                        .channel(NioServerSocketChannel.class)
                        .handler(new LoggingHandler(LogLevel.INFO))
                        .childHandler(new ChannelInitializer<SocketChannel>()
                        {
                            @Override
                            protected void initChannel(SocketChannel ch) throws Exception {
                                ChannelPipeline pipeline = ch.pipeline();
                                pipeline
                                        //基于http协议
                                        .addLast(new HttpServerCodec())
                                        //以块方式写,添加ChunkedWriteHandler处理器
                                        .addLast(new ChunkedWriteHandler())
                                        //http传输过程是分段的,HttpObjectAggregator可以将多个段聚合
                                        .addLast(new HttpObjectAggregator(8 * 1024))
                                        .addLast(new WebSocketServerProtocolHandler("/hello"))
                                        .addLast(new WebSocketServerHandler());
                            }
                        });
                ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
                channelFuture.channel().closeFuture().sync();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            finally {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        }
    }
    
  • 服务端自定义handler

    package com.nic.netty.websocket;
    
    import cn.hutool.core.date.DateUtil;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.SimpleChannelInboundHandler;
    import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
    
    /**
     * Description:
     *
     * @author james
     * @date 2021/7/22 14:58
     */
    public class WebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame>
    {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
            System.out.println("channelRead0 = " + msg.text());
    
            ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器时间:" + DateUtil.now() + " " + msg.text()));
        }
    
        @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
            //id表示唯一的值, longText唯一,shortText不唯一
            System.out.println("handlerAdded  long id = " + ctx.channel().id().asLongText());
            System.out.println("handlerAdded short id = " + ctx.channel().id().asShortText());
        }
    
        @Override
        public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
            System.out.println("handlerRemoved long id = " + ctx.channel().id().asLongText());
        }
    
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            System.out.println("exceptionCaught = " + cause.getMessage());
            ctx.close();
        }
    }
    
  • index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>hello websocket</title>
    </head>
    <body>
    
    
    <script>
        var socket;
        //判断浏览器是否支持websocket
        if (window.WebSocket) {
            socket = new WebSocket("ws://localhost:7103/hello");
            //onmessage 相当于channelRead0
            //data 服务端回复的消息
            socket.onmessage = function (data) {
                var responseText = document.getElementById("responseText");
                console.log(data)
                responseText.value = responseText.value + "\n" + data.data;
            }
            //相当于handlerAdded
            socket.onopen = function (data) {
                var responseText = document.getElementById("responseText");
                responseText.value = "连接开启了。。。"
            }
    
            socket.onclose = function (data) {
                var responseText = document.getElementById("responseText");
                responseText.value = responseText.value + "\n连接关闭了。。。"
            }
        } else {
            alert("当前浏览器不支持websocket")
        }
    
        function send(msg) {
            if (!window.socket) {
                return;
            }
    
            if (socket.readyState === WebSocket.OPEN) {
                socket.send(msg);
                //清空聊天框
                document.getElementById("requestText").value = '';
            } else {
                alert("连接未开启。。。")
            }
        }
    
    </script>
    
    
    <form onsubmit="return false">
        <div style="text-align: center">
            <textarea name="message" id="requestText" style="height: 300px; width: 500px"></textarea>
            <input type="button" value="发消息" onclick="send(this.form.message.value)">
        </div>
        <div style="text-align: center">
            <textarea id="responseText" style="height: 300px; width: 500px"></textarea>
            <input type="button" value="清空内容" onclick="document.getElementById('responseText').value=''">
        </div>
    </form>
    
    </body>
    </html>
    

完整代码 https://github.com/beiJxx/netty_test

资料参考

dongzl.github.io/netty-handb…

cloud.tencent.com/developer/a…

www.cnblogs.com/lsgxeva/p/1…