【Netty 核心技术及源码剖析】02 Netty 核心模块组件

1 Bootstrap、ServerBootstrap

  1. Bootstrap 意思是引导,一个 Netty 应用通常由一个 Bootstrap 开始,主要作用是配置整个 Netty 程序,串联各个组件,Netty 中 Bootstrap 类是客户端程序的启动引导类,ServerBootstrap 是服务端启动引导类。
  2. 常见的方法:
 /**
  * 该方法用于客户端,用来设置一个 EventLoop
  */
 public ServerBootstrap group(EventLoopGroup group);
 /**
  * 该方法用于服务器端,用来设置两个 EventLoop
  */
 public ServerBootstrap group(EventLoopGroup parentGroup, EventLoopGroup childGroup);
 /**
  * 用来给接收到的通道添加配置
  */
 public <T> ServerBootstrap childOption(ChannelOption<T> childOption, T value);
 /**
  * 用来给接收到的通道添加属性
  */
 public <T> ServerBootstrap childAttr(AttributeKey<T> childKey, T value);
 /**
  * 该方法用来设置业务处理类(自定义的 handler)
  */
 public ServerBootstrap childHandler(ChannelHandler childHandler);
 /**
  * 该方法用于服务器端,用来设置占用的端口号
  */
 public ChannelFuture bind(int inetPort);
 /**
  * 该方法用于客户端,用来连接服务器
  */
 public ChannelFuture connect(String inetHost, int inetPort) ;

2 Future、ChannelFuture

  1. Netty 中所有的 IO 操作都是异步的,不能立刻得知消息是否被正确处理。但是可以过一会等它执行完成或者直接注册一个监听,具体的实现就是通过 Future 和 ChannelFutures,他们可以注册一个监听,当操作执行成功或失败时监听会自动触发注册的监听事件。
  2. 常见的方法:
/**
  * 返回当前正在进行 IO 操作的通道
  */
 Channel channel();
 /**
  * 给通道添加监听器
  */
 ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> var1);
 /**
  * 给通道添加监听器
  */
 ChannelFuture addListeners(GenericFutureListener<? extends Future<? super Void>>... var1);
 /**
  * 给通道移除监听器
  */
 ChannelFuture removeListener(GenericFutureListener<? extends Future<? super Void>> var1);
 /**
  * 给通道移除监听器
  */
 ChannelFuture removeListeners(GenericFutureListener<? extends Future<? super Void>>... var1);
 /**
  * 等待任务结束,如果任务产生异常或被中断则抛出异常,否则返回Future自身
  */
 ChannelFuture sync() throws InterruptedException;
 /**
  * 等待任务结束,任务本身不可中断,如果产生异常则抛出异常,否则返回Future自身
  */
 ChannelFuture syncUninterruptibly();
 /**
  * 等待任务结束,如果任务被中断则抛出中断异常,与sync不同的是只抛出中断异常,不抛出任务产生的异常
  */
 ChannelFuture await() throws InterruptedException;
 /**
  * 等待任务结束,任务不可中断
  */
 ChannelFuture awaitUninterruptibly();

3 Channel

4 Selector

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

5 ChannelHandler 及其实现类

  1. ChannelHandler 是一个接口,处理 I/O 事件或拦截 I/O 操作,并将其转发到其 ChannelPipeline(业务处理链)中的下一个处理程序。
  2. ChannelHandler 本身并没有提供很多方法,因为这个接口有许多的方法需要实现,方便使用期间,可以继承它的子类。
  3. ChannelHandler 及其实现类一览图:
    在这里插入图片描述
  • ChannelInboundHandler 用于处理入站 I/O 事件。
  • ChannelOutboundHandler 用于处理出站 I/O 操作。

适配器

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

6 Pipeline 和 ChannelPipeline

  1. ChannelPipeline 是一个 Handler 的集合,它负责处理和拦截 inbound 或者 outbound 的事件和操作,相当于一个贯穿 Netty 的链。
  2. ChannelPipeline 实现了一种高级形式的拦截过滤器模式,使用户可以完全控制事件的处理方式,以及 Channel 中各个的 ChannelHandler 如何相互交互。
  3. 在 Netty 中每个 Channel 都有且仅有一个 ChannelPipeline 与之对应,它们的组成关系如下:
    在这里插入图片描述
  • 一个 Channel 包含了一个 ChannelPipeline,而 ChannelPipeline 中又维护了一个由 ChannelHandlerContext 组成的双向链表,并且每个 ChannelHandlerContext 中又关联着一个 ChannelHandler。
  • 入站事件和出站事件在一个双向链表中,入站事件会从链表 head 往后传递到最后一个入站的 handler,出站事件会从链表 tail 往前传递到最前一个出站的 handler,两种类型的 handler 互不干扰。
  1. 常用方法
    • ChannelPipeline addFirst(ChannelHandler… handlers),把一个业务处理类(handler)添加到链中的第一个位置。
    • ChannelPipeline addLast(ChannelHandler… handlers),把一个业务处理类(handler)添加到链中的最后一个位置。

7 ChannelHandlerContext

  1. 保存 Channel 相关的所有上下文信息,同时关联一个 ChannelHandler 对象。
  2. 即 ChannelHandlerContext 中包含 一 个 具 体 的 事 件 处 理 器 ChannelHandler ,同时 ChannelHandlerContext 中也绑定了对应的 Pipeline 和 Channel 的信息,方便对 ChannelHandler进行调用。
  3. 常用方法:
    1. ChannelOutboundInvoker ChannelFuture close(),关闭通道
    2. ChannelOutboundInvoker ChannelOutboundInvoker flush(),刷新
    3. ChannelFuture writeAndFlush(Object msg) , 将 数 据 写 到 ChannelPipeline 中当前 ChannelHandler 的下一个 ChannelHandler 开始处理(出站)。

8 ChannelOption

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

9 EventLoopGroup 和其实现类 NioEventLoopGroup

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

在这里插入图片描述

  • BossEventLoopGroup 通常是一个单线程的 EventLoop,EventLoop 维护着一个注册了 ServerSocketChannel 的Selector 实例 BossEventLoop 不断轮询 Selector 将连接事件分离出来。接收到 OP_ACCEPT 事件后,将接收到的 SocketChannel 交给 WorkerEventLoopGroup。
  • WorkerEventLoopGroup 会由 next 选择其中一个 EventLoop 来将这个 SocketChannel 注册到其维护的 Selector 并对其后续的 IO 事件进行处理。

10 Unpooled 类

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

public static ByteBuf copiedBuffer(CharSequence string, Charset charset);

ByteBuf 原理图:

BEFORE clear()
    +-------------------+------------------+------------------+
    | discardable bytes |  readable bytes  |  writable bytes  |
    +-------------------+------------------+------------------+
    |                   |                  |                  |
    0      <=      readerIndex   <=   writerIndex    <=    capacity
AFTER clear()
    +---------------------------------------------------------+
    |             writable bytes (got more space)             |
    +---------------------------------------------------------+
    |                                                         |
    0 = readerIndex = writerIndex            <=            capacity
  • capacity:容量,创建时确定。
  • 0 - readerIndex:表示已读
  • readerIndex-writerIndex:表示可读的范围
  • writerIndex - capacity:可写的范围

Bytebuf Demo 代码如下:

package bin.netty.bytebuf;

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

/**
 * @author liyibin
 * @date 2021-06-26
 */
public class ByteBufDemo {

    public static void main(String[] args) {
        ByteBuf byteBuf = Unpooled.copiedBuffer("hello, world", CharsetUtil.UTF_8);

        // buf index
        System.out.println("readerIndex: " + byteBuf.readerIndex() + ", writerIndex: " + byteBuf.writerIndex() + ", capacity: " + byteBuf.capacity());

        for (int i = 0; i < byteBuf.writerIndex(); i++) {
            System.out.println((char) byteBuf.readByte());
        }

        // buf index
        System.out.println("readerIndex: " + byteBuf.readerIndex() + ", writerIndex: " + byteBuf.writerIndex() + ", capacity: " + byteBuf.capacity());

        // 读取部分
        // param1: 起始索引
        // param2: 长度
        System.out.println(byteBuf.getCharSequence(0, 3, CharsetUtil.UTF_8));
    }
}

11 Netty应用实例-群聊系统

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

服务端:

package bin.netty.groupchat;

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.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * @author liyibin
 * @date 2021-06-26
 */
public class NettyGroupChatServer {

    public static void main(String[] args) throws Exception {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap()
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    // 给 bossGroup 添加一个日志处理器
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        // 初始化通道,给 workerGroup 的通道添加处理器
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();

                            // 字符类型解码器
                            pipeline.addLast("decoder", new StringDecoder());
                            // 字符类型编码器
                            pipeline.addLast("encoder", new StringEncoder());

                            // 业务处理器
                            pipeline.addLast(new GroupChatServerHandler());
                        }
                    });

            ChannelFuture channelFuture = serverBootstrap.bind(9999).sync();

            channelFuture.addListener(cf -> {
                if (cf.isSuccess()) {
                    System.out.println("listen on port 9999");
                }
            });

            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

GroupChatServerHandler:

package bin.netty.groupchat;

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;

/**
 * @author liyibin
 * @date 2021-06-26
 */
public class GroupChatServerHandler extends SimpleChannelInboundHandler<String> {

    /**
     * 通道组,用于管理当前连接的通道,全局唯一
     */
    private final static ChannelGroup CHANNELS = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    /**
     * 接收客户端发送的消息
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();

        // 服务端打印消息
        System.out.printf("[%s]: %s\n", channel.remoteAddress().toString(), msg);

        // 给其他通道发送消息
        CHANNELS.forEach(ch -> {
            // 不是当前通讯的通道,就发送消息
            if (ch != channel) {
                ch.writeAndFlush(String.format("[%s]: %s\n", channel.remoteAddress().toString(), msg));
            }
        });
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.printf("%s 加入了群聊\n", ctx.channel().remoteAddress());

        CHANNELS.add(ctx.channel());

        System.out.println("当前群聊用户数:" + CHANNELS.size());
    }

    /**
     * 上线
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.printf("%s 上线了\n", ctx.channel().remoteAddress());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.printf("%s 退出了群聊", ctx.channel().remoteAddress());

        // 会自动移除
        System.out.println("当前群聊用户数:" + CHANNELS.size());
    }

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

客户端:

package bin.netty.groupchat;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
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 io.netty.util.CharsetUtil;

import java.util.Scanner;

/**
 * @author liyibin
 * @date 2021-06-26
 */
public class NettyGroupChatClient {

    public static void main(String[] args) throws Exception {
        NioEventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();

                            // 字符类型解码器
                            pipeline.addLast("decoder", new StringDecoder());
                            // 字符类型编码器
                            pipeline.addLast("encoder", new StringEncoder());

                            pipeline.addLast(new SimpleChannelInboundHandler<String>() {

                                @Override
                                protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
                                    // 打印接收到的消息
                                    System.out.printf("%s\n", msg);
                                }
                            });
                        }

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

            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 9999).sync();

            channelFuture.addListener(cf -> {
                if (cf.isSuccess()) {
                    System.out.println("connect to server");
                }
            });
            Channel channel = channelFuture.channel();

            // 处理用户输入
            Scanner scanner = new Scanner(System.in);

            while (scanner.hasNextLine()) {
                String msg = scanner.nextLine();
                channel.writeAndFlush(Unpooled.copiedBuffer(msg + "\r\n", CharsetUtil.UTF_8));
            }
        } finally {
            group.shutdownGracefully();
        }
    }
}

12 Netty心跳检测机制案例

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

服务端:

package bin.netty.heartcheck;

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;

import java.util.concurrent.TimeUnit;

/**
 * 心跳检测机制
 *
 * @author liyibin
 * @date 2021-06-27
 */
public class NettyHeartCheckServer {

    public static void main(String[] args) throws Exception {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap()
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();

                            // 加入处理空闲状态的处理器
                            // readerIdleTime: 表示多长时间没读,就发送一个心跳检测包
                            // writerIdleTime: 表示多长时间没写,就发送一个心跳检测包
                            // allIdleTime: 表示多长时间没读写,就发送一个心跳检测包
                            // Triggers an {@link IdleStateEvent} when a {@link Channel} has not performed read, write, or both operation for a while.
                            // 当触发 IdleStateEvent 事件时,就会传递给下一个的 handler 的 useEventTriggered 方法处理
                            pipeline.addLast(new IdleStateHandler(3, 5, 7, TimeUnit.SECONDS));

                            // 业务处理器
                            pipeline.addLast(new MyServerHandler());
                        }
                    });

            ChannelFuture channelFuture = serverBootstrap.bind(9999).sync();
            channelFuture.addListener(cf -> {
                if (cf.isSuccess()) {
                    System.out.println("listen on 9999");
                }
            });

            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

MyServerHandler:

package bin.netty.heartcheck;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * @author liyibin
 * @date 2021-06-27
 */
public class MyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            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:
                    eventType = null;
                    break;
            }

            System.out.println(ctx.channel().remoteAddress() + "---空闲类型---" + eventType);
        }
    }
}

客户端:

package bin.netty.heartcheck;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author liyibin
 * @date 2021-06-27
 */
public class NettyHeartCheckClient {

    public static void main(String[] args) throws Exception {
        NioEventLoopGroup 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 {

                        }
                    });

            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 9999).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
}

13 Netty 通过WebSocket编程实现服务器和客户端长连接

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

服务端:

package bin.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;

/**
 * @author liyibin
 * @date 2021-06-27
 */
public class NettyWebSocketServer {

    public static void main(String[] args) throws Exception {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new 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();

                            // http 编解码器
                            pipeline.addLast(new HttpServerCodec());

                            // 以块方式读写
                            pipeline.addLast(new ChunkedWriteHandler());

                            // http 数据传输是分段的,当发送大量数据时,需要将其聚合在一起
                            pipeline.addLast(new HttpObjectAggregator(8192));

                            // 1. websocket 处理器,数据以帧形式传输,netty 中对应 WebSocketFrame类,其下有 6 个子类。
                            // 2. 请求 ws://localhost:9999/chat 进行通讯
                            // 3. WebSocketServerProtocolHandler 核心是将 http 协议提升未 ws 协议,通过响应状态码 101 升级
                            pipeline.addLast(new WebSocketServerProtocolHandler("/chat"));

                            // 业务处理器
                            pipeline.addLast(new MyTextWebSocketFrameHandler());
                        }
                    });

            ChannelFuture channelFuture = serverBootstrap.bind(9999).sync();
            channelFuture.addListener(cf -> {
                if (cf.isSuccess()) {
                    System.out.println("websocket listen on 9999");
                }
            });

            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

MyTextWebSocketFrameHandler:

package bin.netty.websocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.time.LocalDateTime;

/**
 * @author liyibin
 * @date 2021-06-27
 */
public class MyTextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        System.out.printf("[%s]: %s", ctx.channel().remoteAddress(), msg.text());

        // 回复消息
        ctx.writeAndFlush(new TextWebSocketFrame("服务器收到消息: " + LocalDateTime.now()));
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("handlerAdded 被" + ctx.channel().id().asShortText() + " 调用");
        System.out.println("handlerAdded 被" + ctx.channel().id().asLongText() + " 调用");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("handlerRemoved 被" + ctx.channel().id().asShortText() + " 调用");
        System.out.println("handlerRemoved 被" + ctx.channel().id().asLongText() + " 调用");
    }

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

客户端:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <script>
        let socket;
        if (window.WebSocket) {
            socket = new WebSocket("ws://localhost:9999/chat");
            
            socket.onopen = function (evt) {
                let res = document.getElementById("responseText");
                res.value = "连接开启...\n";
            }

            socket.onmessage = function (evt) {
                let res = document.getElementById("responseText");
                res.value = res.value + evt.data;
            }

            socket.onclose = function (evt) {
                let res = document.getElementById("responseText");
                res.value = res.value + "连接关闭...\n";
            }
        } else {
            alert("当前浏览器不支持 WebSocket")
        }

        function send(msg) {
            console.log(msg);

            /*if (!window.socket) {
                console.log("no open");
                return ;
            }*/

            if (socket.readyState === WebSocket.OPEN) {
                socket.send(msg);
            } else {
                alert("连接没有开启")
            }
        }
    </script>
    <form onsubmit="return false">
        <textarea name="message" style="width: 300px; height: 300px"></textarea>
        <input type="button" value="发送消息" onclick="send(this.form.message.value)">

        <textarea id="responseText" style="width: 300px; height: 300px"></textarea>
        <input type="button" value="清空消息" onclick="document.getElementById('responseText').value=''">
    </form>

</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值