Netty网络编程第三卷

x33g5p2x  于2022-02-07 转载在 其他  
字(37.5k)|赞(0)|评价(0)|浏览(467)

三. Netty 进阶

1. 粘包与半包

1.1 粘包现象

服务端代码

  1. /**
  2. * @author zdh
  3. */
  4. public class HelloWorldServer {
  5. static final Logger log = LoggerFactory.getLogger(HelloWorldServer.class);
  6. void start() {
  7. //处理客户端连接
  8. NioEventLoopGroup boss = new NioEventLoopGroup(1);
  9. //处理客户端读写请求
  10. NioEventLoopGroup worker = new NioEventLoopGroup();
  11. try {
  12. ServerBootstrap serverBootstrap = new ServerBootstrap();
  13. serverBootstrap.channel(NioServerSocketChannel.class);
  14. serverBootstrap.group(boss, worker);
  15. //设置接收缓冲区的大小,为了让黏包和半包现象明显
  16. serverBootstrap.option(ChannelOption.SO_RCVBUF,10);
  17. serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
  18. //连接建立时触发
  19. @Override
  20. protected void initChannel(SocketChannel ch) throws Exception {
  21. //Netty的日记输出级别设置
  22. ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
  23. ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
  24. //会在连接建立的时候触发,触发active事件
  25. @Override
  26. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  27. log.debug("connected {}", ctx.channel());
  28. super.channelActive(ctx);
  29. }
  30. //连接断开时触发
  31. @Override
  32. public void channelInactive(ChannelHandlerContext ctx) throws Exception {
  33. log.debug("disconnect {}", ctx.channel());
  34. super.channelInactive(ctx);
  35. }
  36. });
  37. }
  38. });
  39. ChannelFuture channelFuture = serverBootstrap.bind(8080);
  40. log.debug("{} binding...", channelFuture.channel());
  41. channelFuture.sync();
  42. log.debug("{} bound...", channelFuture.channel());
  43. channelFuture.channel().closeFuture().sync();
  44. } catch (InterruptedException e) {
  45. log.error("server error", e);
  46. } finally {
  47. boss.shutdownGracefully();
  48. worker.shutdownGracefully();
  49. log.debug("stoped");
  50. }
  51. }
  52. public static void main(String[] args) {
  53. new HelloWorldServer().start();
  54. }
  55. }

客户端代码希望发送 10 个消息,每个消息是 16 字节

  1. /**
  2. * @author zdh
  3. */
  4. public class HelloWorldClient {
  5. static final Logger log = LoggerFactory.getLogger(HelloWorldClient.class);
  6. public static void main(String[] args) {
  7. NioEventLoopGroup worker = new NioEventLoopGroup();
  8. try {
  9. Bootstrap bootstrap = new Bootstrap();
  10. bootstrap.channel(NioSocketChannel.class);
  11. bootstrap.group(worker);
  12. bootstrap.handler(new ChannelInitializer<SocketChannel>() {
  13. @Override
  14. protected void initChannel(SocketChannel ch) throws Exception {
  15. log.debug("connetted...");
  16. ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
  17. //连接建立成功后,会触发channelActive事件
  18. @Override
  19. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  20. log.debug("sending...");
  21. //总共发送160个字节的数据给服务器端
  22. for (int i = 0; i < 10; i++)
  23. {
  24. //创建一个默认大小为256自己的直接缓冲区
  25. ByteBuf buffer = ctx.alloc().buffer();
  26. //向直接缓冲区中写入16个字节的数据
  27. buffer.writeBytes(new byte[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15});
  28. //发送给服务器
  29. ctx.writeAndFlush(buffer);
  30. }
  31. }
  32. });
  33. }
  34. });
  35. ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 8080).sync();
  36. channelFuture.channel().closeFuture().sync();
  37. } catch (InterruptedException e) {
  38. log.error("client error", e);
  39. } finally {
  40. worker.shutdownGracefully();
  41. }
  42. }
  43. }

1.2 半包现象

客户端代码希望发送 1 个消息,这个消息是 160 字节,代码改为

  1. ByteBuf buffer = ctx.alloc().buffer();
  2. for (int i = 0; i < 10; i++) {
  3. buffer.writeBytes(new byte[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15});
  4. }
  5. ctx.writeAndFlush(buffer);

为现象明显,服务端修改一下接收缓冲区,其它代码不变

  1. serverBootstrap.option(ChannelOption.SO_RCVBUF, 10);

服务器端的某次输出,可以看到接收的消息被分为两节,第一次 20 字节,第二次 140 字节

  1. 08:43:49 [DEBUG] [main] c.i.n.HelloWorldServer - [id: 0x4d6c6a84] binding...
  2. 08:43:49 [DEBUG] [main] c.i.n.HelloWorldServer - [id: 0x4d6c6a84, L:/0:0:0:0:0:0:0:0:8080] bound...
  3. 08:44:23 [DEBUG] [nioEventLoopGroup-3-1] i.n.h.l.LoggingHandler - [id: 0x1719abf7, L:/127.0.0.1:8080 - R:/127.0.0.1:59221] REGISTERED
  4. 08:44:23 [DEBUG] [nioEventLoopGroup-3-1] i.n.h.l.LoggingHandler - [id: 0x1719abf7, L:/127.0.0.1:8080 - R:/127.0.0.1:59221] ACTIVE
  5. 08:44:23 [DEBUG] [nioEventLoopGroup-3-1] c.i.n.HelloWorldServer - connected [id: 0x1719abf7, L:/127.0.0.1:8080 - R:/127.0.0.1:59221]
  6. 08:44:24 [DEBUG] [nioEventLoopGroup-3-1] i.n.h.l.LoggingHandler - [id: 0x1719abf7, L:/127.0.0.1:8080 - R:/127.0.0.1:59221] READ: 20B
  7. +-------------------------------------------------+
  8. | 0 1 2 3 4 5 6 7 8 9 a b c d e f |
  9. +--------+-------------------------------------------------+----------------+
  10. |00000000| 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f |................|
  11. |00000010| 00 01 02 03 |.... |
  12. +--------+-------------------------------------------------+----------------+
  13. 08:44:24 [DEBUG] [nioEventLoopGroup-3-1] i.n.h.l.LoggingHandler - [id: 0x1719abf7, L:/127.0.0.1:8080 - R:/127.0.0.1:59221] READ COMPLETE
  14. 08:44:24 [DEBUG] [nioEventLoopGroup-3-1] i.n.h.l.LoggingHandler - [id: 0x1719abf7, L:/127.0.0.1:8080 - R:/127.0.0.1:59221] READ: 140B
  15. +-------------------------------------------------+
  16. | 0 1 2 3 4 5 6 7 8 9 a b c d e f |
  17. +--------+-------------------------------------------------+----------------+
  18. |00000000| 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 00 01 02 03 |................|
  19. |00000010| 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 00 01 02 03 |................|
  20. |00000020| 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 00 01 02 03 |................|
  21. |00000030| 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 00 01 02 03 |................|
  22. |00000040| 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 00 01 02 03 |................|
  23. |00000050| 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 00 01 02 03 |................|
  24. |00000060| 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 00 01 02 03 |................|
  25. |00000070| 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 00 01 02 03 |................|
  26. |00000080| 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f |............ |
  27. +--------+-------------------------------------------------+----------------+
  28. 08:44:24 [DEBUG] [nioEventLoopGroup-3-1] i.n.h.l.LoggingHandler - [id: 0x1719abf7, L:/127.0.0.1:8080 - R:/127.0.0.1:59221] READ COMPLETE

注意

serverBootstrap.option(ChannelOption.SO_RCVBUF, 10) 影响的底层接收缓冲区(即滑动窗口)大小,仅决定了 netty 读取的最小单位,netty 实际每次读取的一般是它的整数倍

1.3 现象分析

粘包

  • 现象,发送 abc def,接收 abcdef

  • 原因

  • 应用层:接收方 ByteBuf 设置太大(Netty 默认 1024)

  • 滑动窗口:假设发送方 256 bytes 表示一个完整报文,但由于接收方处理不及时且窗口大小足够大,这 256 bytes 字节就会缓冲在接收方的滑动窗口中,当滑动窗口中缓冲了多个报文就会粘包

  • Nagle 算法:会造成粘包

半包

  • 现象,发送 abcdef,接收 abc def

  • 原因

  • 应用层:接收方 ByteBuf 小于实际发送数据量

  • 滑动窗口:假设接收方的窗口只剩了 128 bytes,发送方的报文大小是 256 bytes,这时放不下了,只能先发送前 128 bytes,等待 ack 后才能发送剩余部分,这就造成了半包

  • MSS 限制:当发送的数据超过 MSS 限制后,会将数据切分发送,就会造成半包

本质是因为 TCP 是流式协议,消息无边界

滑动窗口

  • TCP 以一个段(segment)为单位,每发送一个段就需要进行一次确认应答(ack)处理,但如果这么做,缺点是包的往返时间越长性能就越差

  • 为了解决此问题,引入了窗口概念,窗口大小即决定了无需等待应答而可以继续发送的数据最大值

  • 窗口实际就起到一个缓冲区的作用,同时也能起到流量控制的作用

  • 图中深色的部分即要发送的数据,高亮的部分即窗口

  • 窗口内的数据才允许被发送,当应答未到达前,窗口必须停止滑动

  • 如果 1001~2000 这个段的数据 ack 回来了,窗口就可以向前滑动

  • 接收方也会维护一个窗口,只有落在窗口内的数据才能允许接收

MSS 限制
  • 链路层对一次能够发送的最大数据有限制,这个限制称之为 MTU(maximum transmission unit),不同的链路设备的 MTU 值也有所不同,例如
  • 以太网的 MTU 是 1500
  • FDDI(光纤分布式数据接口)的 MTU 是 4352
  • 本地回环地址的 MTU 是 65535 - 本地测试不走网卡
  • MSS (传输层)是最大段长度(maximum segment size),它是 MTU 刨去 tcp 头和 ip 头后剩余能够作为数据传输的字节数
  • ipv4 tcp 头占用 20 bytes,ip 头占用 20 bytes,因此以太网 MSS 的值为 1500 - 40 = 1460
  • TCP 在传递大量数据时,会按照 MSS 大小将数据进行分割发送
  • MSS 的值在三次握手时通知对方自己 MSS 的值,然后在两者之间选择一个小值作为 MSS

Nagle 算法
  • 即使发送一个字节,也需要加入 tcp 头和 ip 头,也就是总字节数会使用 41 bytes,非常不经济。因此为了提高网络利用率,tcp 希望尽可能发送足够大的数据,这就是 Nagle 算法产生的缘由

  • 该算法是指发送端即使还有应该发送的数据,但如果这部分数据很少的话,则进行延迟发送

  • 如果 SO_SNDBUF 的数据达到 MSS,则需要发送

  • 如果 SO_SNDBUF 中含有 FIN(表示需要连接关闭)这时将剩余数据发送,再关闭

  • 如果 TCP_NODELAY = true,则需要发送

  • 已发送的数据都收到 ack 时,则需要发送

  • 上述条件不满足,但发生超时(一般为 200ms)则需要发送

  • 除上述情况,延迟发送

1.4 解决方案

  1. 短链接,发一个包建立一次连接,这样连接建立到连接断开之间就是消息的边界,缺点效率太低
  2. 每一条消息采用固定长度,缺点浪费空间
  3. 每一条消息采用分隔符,例如 \n,缺点需要转义
  4. 每一条消息分为 head 和 body,head 中包含 body 的长度
方法1,短链接

以解决粘包为例

  1. public class HelloWorldClient {
  2. static final Logger log = LoggerFactory.getLogger(HelloWorldClient.class);
  3. public static void main(String[] args) {
  4. // 分 10 次发送
  5. for (int i = 0; i < 10; i++) {
  6. send();
  7. }
  8. }
  9. private static void send() {
  10. NioEventLoopGroup worker = new NioEventLoopGroup();
  11. try {
  12. Bootstrap bootstrap = new Bootstrap();
  13. bootstrap.channel(NioSocketChannel.class);
  14. bootstrap.group(worker);
  15. bootstrap.handler(new ChannelInitializer<SocketChannel>() {
  16. @Override
  17. protected void initChannel(SocketChannel ch) throws Exception {
  18. log.debug("conneted...");
  19. ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
  20. ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
  21. @Override
  22. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  23. log.debug("sending...");
  24. ByteBuf buffer = ctx.alloc().buffer();
  25. buffer.writeBytes(new byte[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15});
  26. ctx.writeAndFlush(buffer);
  27. // 发完即关
  28. ctx.close();
  29. }
  30. });
  31. }
  32. });
  33. ChannelFuture channelFuture = bootstrap.connect("localhost", 8080).sync();
  34. channelFuture.channel().closeFuture().sync();
  35. } catch (InterruptedException e) {
  36. log.error("client error", e);
  37. } finally {
  38. worker.shutdownGracefully();
  39. }
  40. }
  41. }

服务端:

  1. //设置系统的接收缓冲区(滑动窗口)
  2. // serverBootstrap.option(ChannelOption.SO_RCVBUF,10);
  3. //调整netty的接收缓冲区(byteBuf)
  4. serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR,new AdaptiveRecvByteBufAllocator(16,16,16));

SO_RCVBUF和SO_SNDBUF每个套接口都有一个发送缓冲区和一个接收缓冲区,使用这两个套接口选项可以改变缺省缓冲区大小。

当设置TCP套接口接收缓冲区的大小时,函数调用顺序是很重要的,因为TCP的窗口规模选项是在建立连接时用SYN与对方互换得到的。对于客户,SO_RCVBUF选项必须在connect之前设置;对于服务器,SO_RCVBUF选项必须在listen前设置。

设置netty接收缓冲区大小为16字节的情况下:

半包用这种办法还是不好解决,因为接收方的缓冲区大小是有限的

方法2,固定长度

让所有数据包长度固定(假设长度为 8 字节),服务器端加入

  1. //第一个入站处理器
  2. ch.pipeline().addLast(new FixedLengthFrameDecoder(8));

客户端测试代码,注意, 采用这种方法后,客户端什么时候 flush 都可以

  1. public class HelloWorldClient {
  2. static final Logger log = LoggerFactory.getLogger(HelloWorldClient.class);
  3. public static void main(String[] args) {
  4. NioEventLoopGroup worker = new NioEventLoopGroup();
  5. try {
  6. Bootstrap bootstrap = new Bootstrap();
  7. bootstrap.channel(NioSocketChannel.class);
  8. bootstrap.group(worker);
  9. bootstrap.handler(new ChannelInitializer<SocketChannel>() {
  10. @Override
  11. protected void initChannel(SocketChannel ch) throws Exception {
  12. log.debug("connetted...");
  13. ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
  14. ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
  15. @Override
  16. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  17. log.debug("sending...");
  18. // 发送内容随机的数据包
  19. Random r = new Random();
  20. char c = 'a';
  21. ByteBuf buffer = ctx.alloc().buffer();
  22. for (int i = 0; i < 10; i++) {
  23. byte[] bytes = new byte[8];
  24. for (int j = 0; j < r.nextInt(8); j++) {
  25. bytes[j] = (byte) c;
  26. }
  27. c++;
  28. buffer.writeBytes(bytes);
  29. }
  30. ctx.writeAndFlush(buffer);
  31. }
  32. });
  33. }
  34. });
  35. ChannelFuture channelFuture = bootstrap.connect("192.168.0.103", 9090).sync();
  36. channelFuture.channel().closeFuture().sync();
  37. } catch (InterruptedException e) {
  38. log.error("client error", e);
  39. } finally {
  40. worker.shutdownGracefully();
  41. }
  42. }
  43. }

客户端输出

服务端输出

缺点是,数据包的大小不好把握

  • 长度定的太大,浪费
  • 长度定的太小,对某些数据包又显得不够
方法3,固定分隔符

服务端加入,默认以 \n 或 \r\n 作为分隔符,如果超出指定长度仍未出现分隔符,则抛出异常

  1. ch.pipeline().addLast(new LineBasedFrameDecoder(1024));

客户端在每条消息之后,加入 \n 分隔符

  1. public class HelloWorldClient {
  2. static final Logger log = LoggerFactory.getLogger(HelloWorldClient.class);
  3. public static void main(String[] args){
  4. NioEventLoopGroup group = new NioEventLoopGroup();
  5. Channel channel=null;
  6. try{
  7. channel = new Bootstrap()
  8. .group(group)
  9. .channel(NioSocketChannel.class)
  10. .handler(new ChannelInitializer<NioSocketChannel>() {
  11. @Override
  12. protected void initChannel(NioSocketChannel ch) throws Exception {
  13. log.debug("connetted...");
  14. ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
  15. ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
  16. @Override
  17. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  18. log.debug("sending...");
  19. Random r = new Random();
  20. char c = 'a';
  21. ByteBuf buffer = ctx.alloc().buffer();
  22. for (int i = 0; i < 10; i++) {
  23. //随机写入不定长度的数据
  24. for (int j = 1; j <= r.nextInt(16) + 1; j++) {
  25. buffer.writeByte((byte) c);
  26. }
  27. //写入一个换行符
  28. buffer.writeByte(10);
  29. c++;
  30. }
  31. ctx.writeAndFlush(buffer);
  32. }
  33. });
  34. }
  35. }).connect("localhost", 9090)
  36. .sync().channel();
  37. channel.closeFuture().sync();
  38. }
  39. catch (InterruptedException e) {
  40. log.error("client error", e);
  41. } finally
  42. {
  43. group.shutdownGracefully();
  44. }
  45. }
  46. }

缺点,处理字符数据比较合适,但如果内容本身包含了分隔符(字节数据常常会有此情况),那么就会解析错误

方法4,预设长度

在发送消息前,先约定用定长字节表示接下来数据的长度

  1. // 最大长度,长度偏移,长度占用字节,长度调整,剥离字节数
  2. ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024, 0, 1, 0, 1));

主要属性解释:

  • lengthFieldOffset :长度字段偏移量
  • lengthFieldLength: 长度字段长度
  • lengthAdjustment : 长度字段为基准,还有几个字节是内容
  • initialBytesToStrip: 从头剥离几个字节

这里使用测试channel进行测试

  1. public class TestLengthFieldDecoder
  2. {
  3. public static void main(String[] args) {
  4. EmbeddedChannel channel=new EmbeddedChannel(
  5. //初始偏移长度为0,内容长度字段长度,内容长度字段后偏移字节数,剥离长度
  6. new LengthFieldBasedFrameDecoder(1024,0,4,1,4),
  7. new LoggingHandler(LogLevel.DEBUG)
  8. );
  9. //4个字节的内容长度 一个字节的版本号 实际内容长度
  10. ByteBuf buf= ByteBufAllocator.DEFAULT.buffer();
  11. send(buf,"Hello world");
  12. send(buf,"Hi!");
  13. channel.writeInbound(buf);
  14. }
  15. private static void send(ByteBuf buf,String content)
  16. {
  17. //实际内容
  18. byte[] bytes=content.getBytes();
  19. //实际内容长度
  20. int len=bytes.length;
  21. buf.writeInt(len);
  22. //版本号
  23. buf.writeByte(1);
  24. buf.writeBytes(buf);
  25. }
  26. }

下面展示的是没有剥离的情况:

2. 协议设计与解析

2.1 为什么需要协议?

TCP/IP 中消息传输基于流的方式,没有边界。

协议的目的就是划定消息的边界,制定通信双方要共同遵守的通信规则

例如:在网络上传输

  1. 下雨天留客天留我不留

是中文一句著名的无标点符号句子,在没有标点符号情况下,这句话有数种拆解方式,而意思却是完全不同,所以常被用作讲述标点符号的重要性

一种解读

  1. 下雨天留客,天留,我不留

另一种解读

  1. 下雨天,留客天,留我不?留

如何设计协议呢?其实就是给网络传输的信息加上“标点符号”。但通过分隔符来断句不是很好,因为分隔符本身如果用于传输,那么必须加以区分。因此,下面一种协议较为常用

  1. 定长字节表示内容长度 + 实际内容

例如,假设一个中文字符长度为 3,按照上述协议的规则,发送信息方式如下,就不会被接收方弄错意思了

  1. 0f下雨天留客06天留09我不留

小故事

很久很久以前,一位私塾先生到一家任教。双方签订了一纸协议:“无鸡鸭亦可无鱼肉亦可白菜豆腐不可少不得束修金”。此后,私塾先生虽然认真教课,但主人家则总是给私塾先生以白菜豆腐为菜,丝毫未见鸡鸭鱼肉的款待。私塾先生先是很不解,可是后来也就想通了:主人把鸡鸭鱼肉的钱都会换为束修金的,也罢。至此双方相安无事。

年关将至,一个学年段亦告结束。私塾先生临行时,也不见主人家为他交付束修金,遂与主家理论。然主家亦振振有词:“有协议为证——无鸡鸭亦可,无鱼肉亦可,白菜豆腐不可少,不得束修金。这白纸黑字明摆着的,你有什么要说的呢?”

私塾先生据理力争:“协议是这样的——无鸡,鸭亦可;无鱼,肉亦可;白菜豆腐不可,少不得束修金。”

双方唇枪舌战,你来我往,真个是不亦乐乎!

这里的束修金,也作“束脩”,应当是泛指教师应当得到的报酬

2.2 redis 协议举例

简单介绍redis发送数据遵守的协议格式:

  1. set name zhangshan
  2. redis会将上面这条命令看成一个数组
  3. *3 表示数组的长度为3
  4. $3 当前命令的字节数
  5. set
  6. $4 key的字节数
  7. name
  8. $8 value的字节数
  9. zhangshan

客户端实例演示:

  1. @Slf4j
  2. public class RedisClient
  3. {
  4. public static void main(String[] args)
  5. {
  6. NioEventLoopGroup worker = new NioEventLoopGroup();
  7. //byte数组中保存的是分隔符和换行符
  8. byte[] LINE = {13, 10};
  9. try {
  10. Bootstrap bootstrap = new Bootstrap();
  11. bootstrap.channel(NioSocketChannel.class);
  12. bootstrap.group(worker);
  13. bootstrap.handler(new ChannelInitializer<SocketChannel>() {
  14. @Override
  15. protected void initChannel(SocketChannel ch) {
  16. ch.pipeline().addLast(new LoggingHandler());
  17. ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
  18. // 会在连接 channel 建立成功后,会触发 active 事件
  19. @Override
  20. public void channelActive(ChannelHandlerContext ctx) {
  21. set(ctx);
  22. get(ctx);
  23. }
  24. private void get(ChannelHandlerContext ctx) {
  25. ByteBuf buf = ctx.alloc().buffer();
  26. buf.writeBytes("*2".getBytes());
  27. buf.writeBytes(LINE);
  28. buf.writeBytes("$3".getBytes());
  29. buf.writeBytes(LINE);
  30. buf.writeBytes("get".getBytes());
  31. buf.writeBytes(LINE);
  32. buf.writeBytes("$3".getBytes());
  33. buf.writeBytes(LINE);
  34. buf.writeBytes("aaa".getBytes());
  35. buf.writeBytes(LINE);
  36. ctx.writeAndFlush(buf);
  37. }
  38. private void set(ChannelHandlerContext ctx) {
  39. ByteBuf buf = ctx.alloc().buffer();
  40. buf.writeBytes("*3".getBytes());
  41. buf.writeBytes(LINE);
  42. buf.writeBytes("$3".getBytes());
  43. buf.writeBytes(LINE);
  44. buf.writeBytes("set".getBytes());
  45. buf.writeBytes(LINE);
  46. buf.writeBytes("$3".getBytes());
  47. buf.writeBytes(LINE);
  48. buf.writeBytes("aaa".getBytes());
  49. buf.writeBytes(LINE);
  50. buf.writeBytes("$3".getBytes());
  51. buf.writeBytes(LINE);
  52. buf.writeBytes("bbb".getBytes());
  53. buf.writeBytes(LINE);
  54. ctx.writeAndFlush(buf);
  55. }
  56. @Override
  57. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  58. ByteBuf buf = (ByteBuf) msg;
  59. System.out.println(buf.toString(Charset.defaultCharset()));
  60. }
  61. });
  62. }
  63. });
  64. ChannelFuture channelFuture = bootstrap.connect("localhost", 6379).sync();
  65. channelFuture.channel().closeFuture().sync();
  66. } catch (InterruptedException e) {
  67. log.error("client error", e);
  68. } finally {
  69. worker.shutdownGracefully();
  70. }
  71. }
  72. }

可以就可以看出,互联网通就是由不同的协议构成的,redis通信也遵循自己的协议,只要客户端发送的数据遵循了redis协议,redis服务器收到了就可以解析数据,做出响应

2.3 http 协议举例

netty实现了http协议的类如下,该类从名字上可以看出,可以完成http协议的编解码功能,即解析浏览器发送的http请求数据,然后将响应给浏览器的数据进行编码,编码为符合http协议的数据响应格式,方便浏览器解析

  1. HttpServerCodec,该类既是入站处理器,也是出站处理器

HttpServer服务端‘’

  1. @Slf4j
  2. public class HttpServer
  3. {
  4. public static void main(String[] args)
  5. {
  6. NioEventLoopGroup boss = new NioEventLoopGroup();
  7. NioEventLoopGroup worker = new NioEventLoopGroup();
  8. try {
  9. ServerBootstrap serverBootstrap = new ServerBootstrap();
  10. serverBootstrap.channel(NioServerSocketChannel.class);
  11. serverBootstrap.group(boss, worker);
  12. serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
  13. @Override
  14. protected void initChannel(SocketChannel ch) throws Exception {
  15. ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
  16. //编解码器
  17. ch.pipeline().addLast(new HttpServerCodec());
  18. //对编解码器的结果进行处理
  19. ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
  20. @Override
  21. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  22. log.debug("{}", msg.getClass());
  23. if (msg instanceof HttpRequest)
  24. { // 请求行,请求头
  25. }
  26. else if (msg instanceof HttpContent) { //请求体
  27. }
  28. }
  29. });
  30. }
  31. });
  32. ChannelFuture channelFuture = serverBootstrap.bind(8080).sync();
  33. channelFuture.channel().closeFuture().sync();
  34. } catch (InterruptedException e) {
  35. log.error("server error", e);
  36. } finally {
  37. boss.shutdownGracefully();
  38. worker.shutdownGracefully();
  39. }
  40. }
  41. }

但是上面区分请求头和请求体的代码不够优雅,可以写成下面这样:

  1. 只关心指定消息的处理器,非指定类型的消息,当前处理器会选择跳过不处理
  2. SimpleChannelInboundHandler<HttpRequest>()
  1. //对编解码器的结果进行处理
  2. ch.pipeline().addLast(new SimpleChannelInboundHandler<HttpRequest>() {
  3. @Override
  4. protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception {
  5. // 获取请求
  6. log.debug(msg.uri());
  7. // 返回响应
  8. DefaultFullHttpResponse response =
  9. new DefaultFullHttpResponse(msg.protocolVersion(), HttpResponseStatus.OK);
  10. byte[] bytes = "<h1>Hello, world!</h1>".getBytes();
  11. //如果不加响应头标注响应数据长度,浏览器会一直转圈圈等待客户端将剩余数据传输过来
  12. response.headers().setInt(CONTENT_LENGTH, bytes.length);
  13. response.content().writeBytes(bytes);
  14. // 写回响应
  15. ctx.writeAndFlush(response);
  16. }
  17. });

2.4 自定义协议要素

  • 魔数,用来在第一时间判定是否是无效数据包
  • 版本号,可以支持协议的升级
  • 序列化算法,消息正文到底采用哪种序列化反序列化方式,可以由此扩展,例如:json、protobuf、hessian、jdk
  • 指令类型,是登录、注册、单聊、群聊… 跟业务相关
  • 请求序号,为了双工通信,提供异步能力
  • 正文长度
  • 消息正文
编解码器

根据上面的要素,设计一个登录请求消息和登录响应消息,并使用 Netty 完成收发

  1. package dhy.com.protocol;
  2. import dhy.com.message.Message;
  3. import io.netty.buffer.ByteBuf;
  4. import io.netty.channel.ChannelHandlerContext;
  5. import io.netty.handler.codec.ByteToMessageCodec;
  6. import lombok.extern.slf4j.Slf4j;
  7. import java.io.ByteArrayInputStream;
  8. import java.io.ByteArrayOutputStream;
  9. import java.io.ObjectInputStream;
  10. import java.io.ObjectOutputStream;
  11. import java.util.List;
  12. /**
  13. * <P>
  14. * 消息的编解码器
  15. * </P>
  16. * @author zdh
  17. */
  18. @Slf4j
  19. public class MessageCodec extends ByteToMessageCodec<Message> {
  20. /**
  21. * <P>
  22. * 消息编码器
  23. * </P>
  24. * @param ctx
  25. * @param msg
  26. * @param out
  27. * @throws Exception
  28. */
  29. @Override
  30. public void encode(ChannelHandlerContext ctx, Message msg, ByteBuf out) throws Exception {
  31. // 1. 4 字节的魔数
  32. out.writeBytes(new byte[]{1, 2, 3, 4});
  33. // 2. 1 字节的版本,
  34. out.writeByte(1);
  35. // 3. 1 字节的序列化方式 jdk 0 , json 1
  36. out.writeByte(0);
  37. // 4. 1 字节的指令类型
  38. out.writeByte(msg.getMessageType());
  39. // 5. 4 个字节
  40. out.writeInt(msg.getSequenceId());
  41. // 无意义,对齐填充 ---一般都是16的整数倍
  42. out.writeByte(0xff);
  43. // 6. 获取内容的字节数组
  44. //这里假定使用jdk序列化方式写出数据
  45. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  46. ObjectOutputStream oos = new ObjectOutputStream(bos);
  47. oos.writeObject(msg);
  48. byte[] bytes = bos.toByteArray();
  49. // 7. 长度
  50. out.writeInt(bytes.length);
  51. // 8. 写入内容
  52. out.writeBytes(bytes);
  53. }
  54. /**
  55. * <P>
  56. * 消息解码器
  57. * </P>
  58. * @param ctx
  59. * @param in
  60. * @param out
  61. * @throws Exception
  62. */
  63. @Override
  64. protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
  65. //1.读取魔数
  66. int magicNum = in.readInt();
  67. //2.版本
  68. byte version = in.readByte();
  69. //3.序列化方式
  70. byte serializerType = in.readByte();
  71. //4.指令类型
  72. byte messageType = in.readByte();
  73. //5.消息的序号
  74. int sequenceId = in.readInt();
  75. //6.读取填充字节---无意义
  76. in.readByte();
  77. //7.读取数据长度
  78. int length = in.readInt();
  79. byte[] bytes = new byte[length];
  80. //8.按照指定长度读取数据
  81. in.readBytes(bytes, 0, length);
  82. //序列化方式读取出数据
  83. ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
  84. Message message = (Message) ois.readObject();
  85. log.debug("{}, {}, {}, {}, {}, {}", magicNum, version, serializerType, messageType, sequenceId, length);
  86. log.debug("{}", message);
  87. //将解码后的数据加入消息集合
  88. out.add(message);
  89. }
  90. }

测试

  1. package dhy.test;
  2. import dhy.com.message.LoginRequestMessage;
  3. import dhy.com.protocol.MessageCodec;
  4. import io.netty.channel.embedded.EmbeddedChannel;
  5. import io.netty.handler.logging.LoggingHandler;
  6. import lombok.extern.slf4j.Slf4j;
  7. import org.junit.jupiter.api.Test;
  8. /**
  9. * @author 大忽悠
  10. * @create 2022/1/23 16:34
  11. */
  12. @Slf4j
  13. public class DhyTest
  14. {
  15. @Test
  16. public void test() throws Exception {
  17. EmbeddedChannel channel = new EmbeddedChannel
  18. (
  19. //打印日志
  20. new LoggingHandler(),
  21. //自定义的编解码器---入站和出站处理器
  22. new MessageCodec()
  23. );
  24. //encode
  25. LoginRequestMessage message = new LoginRequestMessage("zhangsan", "123");
  26. //将数据交给出站处理器处理
  27. channel.writeOutbound(message);
  28. }
  29. }

解读

解码测试:

  1. @Slf4j
  2. public class DhyTest
  3. {
  4. @Test
  5. public void test() throws Exception
  6. {
  7. EmbeddedChannel channel =
  8. new EmbeddedChannel
  9. (
  10. //打印日志
  11. new LoggingHandler(),
  12. //自定义的编解码器---入站和出站处理器
  13. new MessageCodec()
  14. );
  15. //encode
  16. LoginRequestMessage message = new LoginRequestMessage("zhangsan", "123");
  17. //将数据交给出站处理器处理
  18. // channel.writeOutbound(message);
  19. //decode
  20. ByteBuf buf = ByteBufAllocator.DEFAULT.buffer();
  21. //将message对象编码后,写入缓冲区中
  22. new MessageCodec().encode(null, message, buf);
  23. //写入数据,交给入站处理器处理数据
  24. channel.writeInbound(buf);
  25. }
  26. }

半包问题:如果出现了半包问题,可能会导致序列化失败问题

通过切片模拟半包问题:

  1. ByteBuf s1 = buf.slice(0, 100);
  2. ByteBuf s2 = buf.slice(100, buf.readableBytes() - 100);
  3. s1.retain(); // 引用计数 2
  4. channel.writeInbound(s1); // release 1
  5. channel.writeInbound(s2);

这里会走两次decode方法,因为第一次数据没有读取完毕,第二次会将没读取完的数据继续进行解码处理,结果发现解析过程不符合格式报错

解决方法:帧解码器,只有当解码器读够了数据,才会将数据传给下一个处理器进行处理

  1. /**
  2. * @author 大忽悠
  3. * @create 2022/1/23 16:34
  4. */
  5. @Slf4j
  6. public class DhyTest
  7. {
  8. @Test
  9. public void test() throws Exception
  10. {
  11. EmbeddedChannel channel =
  12. new EmbeddedChannel
  13. (
  14. //打印日志
  15. new LoggingHandler(),
  16. //最大数据长度为1024个字节
  17. //长度字段偏移量 12
  18. //长度字段大小 4
  19. //长度往后多少是内容数据 0
  20. //剥离长度 0
  21. new LengthFieldBasedFrameDecoder(
  22. 1024, 12,
  23. 4, 0, 0),
  24. //自定义的编解码器---入站和出站处理器
  25. new MessageCodec()
  26. );
  27. //encode
  28. LoginRequestMessage message = new LoginRequestMessage("zhangsan", "123");
  29. //将数据交给出站处理器处理
  30. // channel.writeOutbound(message);
  31. //decode
  32. ByteBuf buf = ByteBufAllocator.DEFAULT.buffer();
  33. //将message对象编码后,写入缓冲区中
  34. new MessageCodec().encode(null, message, buf);
  35. ByteBuf s1 = buf.slice(0, 100);
  36. ByteBuf s2 = buf.slice(100, buf.readableBytes() - 100);
  37. s1.retain(); // 引用计数 2
  38. channel.writeInbound(s1); // release 1
  39. channel.writeInbound(s2);
  40. }
  41. }

线程安全性

LengthFieldBasedFrameDecoder是非线程安全的,因为它会保存读取的状态,如果两个线程同时调用该解码器,并且第一个线程出现了半包问题,那么当前解码器会保存读取一半的数据;此时另一个线程也调用该解码器,那么解码器会错误的吧当前线程的数据域之前另一个线程读取一半的数据进行拼接然后返回给下一个入站处理器进行处理

netty在设计的时候就考虑到了这点,因此对于可以共享的处理器类上面都加上了sharable注解

💡 什么时候可以加 @Sharable
  • 当 handler 不保存状态时,就可以安全地在多线程下被共享
  • 但要注意对于编解码器类,不能继承 ByteToMessageCodec 或 CombinedChannelDuplexHandler 父类,他们的构造方法对 @Sharable 有限制
  • 如果能确保编解码器不会保存状态,可以继承 MessageToMessageCodec 父类
  1. @Slf4j
  2. @ChannelHandler.Sharable
  3. /**
  4. * 必须和 LengthFieldBasedFrameDecoder 一起使用,确保接到的 ByteBuf 消息是完整的
  5. */
  6. public class MessageCodecSharable extends MessageToMessageCodec<ByteBuf, Message> {
  7. @Override
  8. protected void encode(ChannelHandlerContext ctx, Message msg, List<Object> outList) throws Exception {
  9. ByteBuf out = ctx.alloc().buffer();
  10. // 1. 4 字节的魔数
  11. out.writeBytes(new byte[]{1, 2, 3, 4});
  12. // 2. 1 字节的版本,
  13. out.writeByte(1);
  14. // 3. 1 字节的序列化方式 jdk 0 , json 1
  15. out.writeByte(0);
  16. // 4. 1 字节的指令类型
  17. out.writeByte(msg.getMessageType());
  18. // 5. 4 个字节
  19. out.writeInt(msg.getSequenceId());
  20. // 无意义,对齐填充
  21. out.writeByte(0xff);
  22. // 6. 获取内容的字节数组
  23. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  24. ObjectOutputStream oos = new ObjectOutputStream(bos);
  25. oos.writeObject(msg);
  26. byte[] bytes = bos.toByteArray();
  27. // 7. 长度
  28. out.writeInt(bytes.length);
  29. // 8. 写入内容
  30. out.writeBytes(bytes);
  31. outList.add(out);
  32. }
  33. @Override
  34. protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
  35. int magicNum = in.readInt();
  36. byte version = in.readByte();
  37. byte serializerType = in.readByte();
  38. byte messageType = in.readByte();
  39. int sequenceId = in.readInt();
  40. in.readByte();
  41. int length = in.readInt();
  42. byte[] bytes = new byte[length];
  43. in.readBytes(bytes, 0, length);
  44. ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
  45. Message message = (Message) ois.readObject();
  46. log.debug("{}, {}, {}, {}, {}, {}", magicNum, version, serializerType, messageType, sequenceId, length);
  47. log.debug("{}", message);
  48. out.add(message);
  49. }
  50. }

3. 聊天室案例

3.1 聊天室业务介绍

  • 用户管理接口
  1. /**
  2. * 用户管理接口
  3. */
  4. public interface UserService {
  5. /**
  6. * 登录
  7. * @param username 用户名
  8. * @param password 密码
  9. * @return 登录成功返回 true, 否则返回 false
  10. */
  11. boolean login(String username, String password);
  12. }
  • 用户管理接口实现类,默认基于内存实现
  1. public class UserServiceMemoryImpl implements UserService {
  2. private Map<String, String> allUserMap = new ConcurrentHashMap<>();
  3. {
  4. allUserMap.put("zhangsan", "123");
  5. allUserMap.put("lisi", "123");
  6. allUserMap.put("wangwu", "123");
  7. allUserMap.put("zhaoliu", "123");
  8. allUserMap.put("qianqi", "123");
  9. }
  10. @Override
  11. public boolean login(String username, String password) {
  12. String pass = allUserMap.get(username);
  13. if (pass == null) {
  14. return false;
  15. }
  16. return pass.equals(password);
  17. }
  18. }
  • 会话管理接口
  1. /**
  2. * 会话管理接口
  3. */
  4. public interface Session {
  5. /**
  6. * 绑定会话
  7. * @param channel 哪个 channel 要绑定会话
  8. * @param username 会话绑定用户
  9. */
  10. void bind(Channel channel, String username);
  11. /**
  12. * 解绑会话
  13. * @param channel 哪个 channel 要解绑会话
  14. */
  15. void unbind(Channel channel);
  16. /**
  17. * 获取属性
  18. * @param channel 哪个 channel
  19. * @param name 属性名
  20. * @return 属性值
  21. */
  22. Object getAttribute(Channel channel, String name);
  23. /**
  24. * 设置属性
  25. * @param channel 哪个 channel
  26. * @param name 属性名
  27. * @param value 属性值
  28. */
  29. void setAttribute(Channel channel, String name, Object value);
  30. /**
  31. * 根据用户名获取 channel
  32. * @param username 用户名
  33. * @return channel
  34. */
  35. Channel getChannel(String username);
  36. }
  • 基于内存的session会话接口实现类
  1. public class SessionMemoryImpl implements Session {
  2. private final Map<String, Channel> usernameChannelMap = new ConcurrentHashMap<>();
  3. private final Map<Channel, String> channelUsernameMap = new ConcurrentHashMap<>();
  4. private final Map<Channel,Map<String,Object>> channelAttributesMap = new ConcurrentHashMap<>();
  5. @Override
  6. public void bind(Channel channel, String username) {
  7. usernameChannelMap.put(username, channel);
  8. channelUsernameMap.put(channel, username);
  9. channelAttributesMap.put(channel, new ConcurrentHashMap<>());
  10. }
  11. @Override
  12. public void unbind(Channel channel) {
  13. String username = channelUsernameMap.remove(channel);
  14. usernameChannelMap.remove(username);
  15. channelAttributesMap.remove(channel);
  16. }
  17. @Override
  18. public Object getAttribute(Channel channel, String name) {
  19. return channelAttributesMap.get(channel).get(name);
  20. }
  21. @Override
  22. public void setAttribute(Channel channel, String name, Object value) {
  23. channelAttributesMap.get(channel).put(name, value);
  24. }
  25. @Override
  26. public Channel getChannel(String username) {
  27. return usernameChannelMap.get(username);
  28. }
  29. @Override
  30. public String toString() {
  31. return usernameChannelMap.toString();
  32. }
  33. }
  • session工厂,用来获取session实例对象
  1. public abstract class SessionFactory {
  2. private static Session session = new SessionMemoryImpl();
  3. public static Session getSession() {
  4. return session;
  5. }
  6. }
  • 聊天组
  1. @Data
  2. /**
  3. * 聊天组,即聊天室
  4. */
  5. public class Group {
  6. // 聊天室名称
  7. private String name;
  8. // 聊天室成员
  9. private Set<String> members;
  10. public static final Group EMPTY_GROUP = new Group("empty", Collections.emptySet());
  11. public Group(String name, Set<String> members) {
  12. this.name = name;
  13. this.members = members;
  14. }
  15. }
  • 聊天组会话管理接口
  1. /**
  2. * 聊天组会话管理接口
  3. */
  4. public interface GroupSession {
  5. /**
  6. * 创建一个聊天组, 如果不存在才能创建成功, 否则返回 null
  7. * @param name 组名
  8. * @param members 成员
  9. * @return 成功时返回组对象, 失败返回 null
  10. */
  11. Group createGroup(String name, Set<String> members);
  12. /**
  13. * 加入聊天组
  14. * @param name 组名
  15. * @param member 成员名
  16. * @return 如果组不存在返回 null, 否则返回组对象
  17. */
  18. Group joinMember(String name, String member);
  19. /**
  20. * 移除组成员
  21. * @param name 组名
  22. * @param member 成员名
  23. * @return 如果组不存在返回 null, 否则返回组对象
  24. */
  25. Group removeMember(String name, String member);
  26. /**
  27. * 移除聊天组
  28. * @param name 组名
  29. * @return 如果组不存在返回 null, 否则返回组对象
  30. */
  31. Group removeGroup(String name);
  32. /**
  33. * 获取组成员
  34. * @param name 组名
  35. * @return 成员集合, 如果群不存在或没有成员会返回 empty set
  36. */
  37. Set<String> getMembers(String name);
  38. /**
  39. * 获取组成员的 channel 集合, 只有在线的 channel 才会返回
  40. * @param name 组名
  41. * @return 成员 channel 集合
  42. */
  43. List<Channel> getMembersChannel(String name);
  44. }
  • 基于内存的聊天组会话接口实现类,ConcurrentHashMap是为了确保操作的原子性,防止并发问题
  1. public class GroupSessionMemoryImpl implements GroupSession {
  2. private final Map<String, Group> groupMap = new ConcurrentHashMap<>();
  3. @Override
  4. public Group createGroup(String name, Set<String> members) {
  5. Group group = new Group(name, members);
  6. return groupMap.putIfAbsent(name, group);
  7. }
  8. @Override
  9. public Group joinMember(String name, String member) {
  10. return groupMap.computeIfPresent(name, (key, value) -> {
  11. value.getMembers().add(member);
  12. return value;
  13. });
  14. }
  15. @Override
  16. public Group removeMember(String name, String member) {
  17. return groupMap.computeIfPresent(name, (key, value) -> {
  18. value.getMembers().remove(member);
  19. return value;
  20. });
  21. }
  22. @Override
  23. public Group removeGroup(String name) {
  24. return groupMap.remove(name);
  25. }
  26. @Override
  27. public Set<String> getMembers(String name) {
  28. return groupMap.getOrDefault(name, Group.EMPTY_GROUP).getMembers();
  29. }
  30. @Override
  31. public List<Channel> getMembersChannel(String name) {
  32. return getMembers(name).stream()
  33. .map(member -> SessionFactory.getSession().getChannel(member))
  34. .filter(Objects::nonNull)
  35. .collect(Collectors.toList());
  36. }
  37. }
  • 会话组session工厂
  1. public abstract class GroupSessionFactory {
  2. private static GroupSession session = new GroupSessionMemoryImpl();
  3. public static GroupSession getGroupSession() {
  4. return session;
  5. }
  6. }

3.2 聊天室业务

  1. @Slf4j
  2. public class ChatServer {
  3. public static void main(String[] args) {
  4. NioEventLoopGroup boss = new NioEventLoopGroup();
  5. NioEventLoopGroup worker = new NioEventLoopGroup();
  6. LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
  7. MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
  8. try {
  9. ServerBootstrap serverBootstrap = new ServerBootstrap();
  10. serverBootstrap.channel(NioServerSocketChannel.class);
  11. serverBootstrap.group(boss, worker);
  12. serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
  13. @Override
  14. protected void initChannel(SocketChannel ch) throws Exception {
  15. ch.pipeline().addLast(new ProcotolFrameDecoder());
  16. ch.pipeline().addLast(LOGGING_HANDLER);
  17. ch.pipeline().addLast(MESSAGE_CODEC);
  18. ch.pipeline().addLast(new SimpleChannelInboundHandler<LoginRequestMessage>() {
  19. @Override
  20. protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {
  21. String username = msg.getUsername();
  22. String password = msg.getPassword();
  23. boolean login = UserServiceFactory.getUserService().login(username, password);
  24. LoginResponseMessage message;
  25. if(login) {
  26. message = new LoginResponseMessage(true, "登录成功");
  27. } else {
  28. message = new LoginResponseMessage(false, "用户名或密码不正确");
  29. }
  30. ctx.writeAndFlush(message);
  31. }
  32. });
  33. }
  34. });
  35. Channel channel = serverBootstrap.bind(8080).sync().channel();
  36. channel.closeFuture().sync();
  37. } catch (InterruptedException e) {
  38. log.error("server error", e);
  39. } finally {
  40. boss.shutdownGracefully();
  41. worker.shutdownGracefully();
  42. }
  43. }
  44. }
  1. @Slf4j
  2. public class ChatClient {
  3. public static void main(String[] args) {
  4. NioEventLoopGroup group = new NioEventLoopGroup();
  5. LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
  6. MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
  7. CountDownLatch WAIT_FOR_LOGIN = new CountDownLatch(1);
  8. AtomicBoolean LOGIN = new AtomicBoolean(false);
  9. try {
  10. Bootstrap bootstrap = new Bootstrap();
  11. bootstrap.channel(NioSocketChannel.class);
  12. bootstrap.group(group);
  13. bootstrap.handler(new ChannelInitializer<SocketChannel>() {
  14. @Override
  15. protected void initChannel(SocketChannel ch) throws Exception {
  16. ch.pipeline().addLast(new ProcotolFrameDecoder());
  17. // ch.pipeline().addLast(LOGGING_HANDLER);
  18. ch.pipeline().addLast(MESSAGE_CODEC);
  19. ch.pipeline().addLast("client handler", new ChannelInboundHandlerAdapter() {
  20. // 接收响应消息
  21. @Override
  22. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  23. log.debug("msg: {}", msg);
  24. if ((msg instanceof LoginResponseMessage)) {
  25. LoginResponseMessage response = (LoginResponseMessage) msg;
  26. if (response.isSuccess()) {
  27. // 如果登录成功
  28. LOGIN.set(true);
  29. }
  30. // 唤醒 system in 线程
  31. WAIT_FOR_LOGIN.countDown();
  32. }
  33. }
  34. // 在连接建立后触发 active 事件
  35. @Override
  36. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  37. // 负责接收用户在控制台的输入,负责向服务器发送各种消息
  38. new Thread(() -> {
  39. Scanner scanner = new Scanner(System.in);
  40. System.out.println("请输入用户名:");
  41. String username = scanner.nextLine();
  42. System.out.println("请输入密码:");
  43. String password = scanner.nextLine();
  44. // 构造消息对象
  45. LoginRequestMessage message = new LoginRequestMessage(username, password);
  46. // 发送消息
  47. ctx.writeAndFlush(message);
  48. System.out.println("等待后续操作...");
  49. try {
  50. WAIT_FOR_LOGIN.await();
  51. } catch (InterruptedException e) {
  52. e.printStackTrace();
  53. }
  54. // 如果登录失败
  55. if (!LOGIN.get()) {
  56. ctx.channel().close();
  57. return;
  58. }
  59. while (true) {
  60. System.out.println("==================================");
  61. System.out.println("send [username] [content]");
  62. System.out.println("gsend [group name] [content]");
  63. System.out.println("gcreate [group name] [m1,m2,m3...]");
  64. System.out.println("gmembers [group name]");
  65. System.out.println("gjoin [group name]");
  66. System.out.println("gquit [group name]");
  67. System.out.println("quit");
  68. System.out.println("==================================");
  69. String command = scanner.nextLine();
  70. String[] s = command.split(" ");
  71. switch (s[0]){
  72. case "send":
  73. ctx.writeAndFlush(new ChatRequestMessage(username, s[1], s[2]));
  74. break;
  75. case "gsend":
  76. ctx.writeAndFlush(new GroupChatRequestMessage(username, s[1], s[2]));
  77. break;
  78. case "gcreate":
  79. Set<String> set = new HashSet<>(Arrays.asList(s[2].split(",")));
  80. set.add(username); // 加入自己
  81. ctx.writeAndFlush(new GroupCreateRequestMessage(s[1], set));
  82. break;
  83. case "gmembers":
  84. ctx.writeAndFlush(new GroupMembersRequestMessage(s[1]));
  85. break;
  86. case "gjoin":
  87. ctx.writeAndFlush(new GroupJoinRequestMessage(username, s[1]));
  88. break;
  89. case "gquit":
  90. ctx.writeAndFlush(new GroupQuitRequestMessage(username, s[1]));
  91. break;
  92. case "quit":
  93. ctx.channel().close();
  94. return;
  95. }
  96. }
  97. }, "system in").start();
  98. }
  99. });
  100. }
  101. });
  102. Channel channel = bootstrap.connect("localhost", 8080).sync().channel();
  103. channel.closeFuture().sync();
  104. } catch (Exception e) {
  105. log.error("client error", e);
  106. } finally {
  107. group.shutdownGracefully();
  108. }
  109. }
  110. }

3.3 聊天室业务-单聊

服务器端将 handler 独立出来

登录 handler

  1. @ChannelHandler.Sharable
  2. public class LoginRequestMessageHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {
  3. @Override
  4. protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {
  5. String username = msg.getUsername();
  6. String password = msg.getPassword();
  7. boolean login = UserServiceFactory.getUserService().login(username, password);
  8. LoginResponseMessage message;
  9. if(login) {
  10. SessionFactory.getSession().bind(ctx.channel(), username);
  11. message = new LoginResponseMessage(true, "登录成功");
  12. } else {
  13. message = new LoginResponseMessage(false, "用户名或密码不正确");
  14. }
  15. ctx.writeAndFlush(message);
  16. }
  17. }

单聊 handler

  1. @ChannelHandler.Sharable
  2. public class ChatRequestMessageHandler extends SimpleChannelInboundHandler<ChatRequestMessage> {
  3. @Override
  4. protected void channelRead0(ChannelHandlerContext ctx, ChatRequestMessage msg) throws Exception {
  5. String to = msg.getTo();
  6. Channel channel = SessionFactory.getSession().getChannel(to);
  7. // 在线
  8. if(channel != null) {
  9. channel.writeAndFlush(new ChatResponseMessage(msg.getFrom(), msg.getContent()));
  10. }
  11. // 不在线
  12. else {
  13. ctx.writeAndFlush(new ChatResponseMessage(false, "对方用户不存在或者不在线"));
  14. }
  15. }
  16. }

3.4 聊天室业务-群聊

创建群聊

  1. @ChannelHandler.Sharable
  2. public class GroupCreateRequestMessageHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {
  3. @Override
  4. protected void channelRead0(ChannelHandlerContext ctx, GroupCreateRequestMessage msg) throws Exception {
  5. String groupName = msg.getGroupName();
  6. Set<String> members = msg.getMembers();
  7. // 群管理器
  8. GroupSession groupSession = GroupSessionFactory.getGroupSession();
  9. Group group = groupSession.createGroup(groupName, members);
  10. if (group == null) {
  11. // 发生成功消息
  12. ctx.writeAndFlush(new GroupCreateResponseMessage(true, groupName + "创建成功"));
  13. // 发送拉群消息
  14. List<Channel> channels = groupSession.getMembersChannel(groupName);
  15. for (Channel channel : channels) {
  16. channel.writeAndFlush(new GroupCreateResponseMessage(true, "您已被拉入" + groupName));
  17. }
  18. } else {
  19. ctx.writeAndFlush(new GroupCreateResponseMessage(false, groupName + "已经存在"));
  20. }
  21. }
  22. }

群聊

  1. @ChannelHandler.Sharable
  2. public class GroupChatRequestMessageHandler extends SimpleChannelInboundHandler<GroupChatRequestMessage> {
  3. @Override
  4. protected void channelRead0(ChannelHandlerContext ctx, GroupChatRequestMessage msg) throws Exception {
  5. List<Channel> channels = GroupSessionFactory.getGroupSession()
  6. .getMembersChannel(msg.getGroupName());
  7. for (Channel channel : channels) {
  8. channel.writeAndFlush(new GroupChatResponseMessage(msg.getFrom(), msg.getContent()));
  9. }
  10. }
  11. }

加入群聊

  1. @ChannelHandler.Sharable
  2. public class GroupJoinRequestMessageHandler extends SimpleChannelInboundHandler<GroupJoinRequestMessage> {
  3. @Override
  4. protected void channelRead0(ChannelHandlerContext ctx, GroupJoinRequestMessage msg) throws Exception {
  5. Group group = GroupSessionFactory.getGroupSession().joinMember(msg.getGroupName(), msg.getUsername());
  6. if (group != null) {
  7. ctx.writeAndFlush(new GroupJoinResponseMessage(true, msg.getGroupName() + "群加入成功"));
  8. } else {
  9. ctx.writeAndFlush(new GroupJoinResponseMessage(true, msg.getGroupName() + "群不存在"));
  10. }
  11. }
  12. }

退出群聊

  1. @ChannelHandler.Sharable
  2. public class GroupQuitRequestMessageHandler extends SimpleChannelInboundHandler<GroupQuitRequestMessage> {
  3. @Override
  4. protected void channelRead0(ChannelHandlerContext ctx, GroupQuitRequestMessage msg) throws Exception {
  5. Group group = GroupSessionFactory.getGroupSession().removeMember(msg.getGroupName(), msg.getUsername());
  6. if (group != null) {
  7. ctx.writeAndFlush(new GroupJoinResponseMessage(true, "已退出群" + msg.getGroupName()));
  8. } else {
  9. ctx.writeAndFlush(new GroupJoinResponseMessage(true, msg.getGroupName() + "群不存在"));
  10. }
  11. }
  12. }

查看成员

  1. @ChannelHandler.Sharable
  2. public class GroupMembersRequestMessageHandler extends SimpleChannelInboundHandler<GroupMembersRequestMessage> {
  3. @Override
  4. protected void channelRead0(ChannelHandlerContext ctx, GroupMembersRequestMessage msg) throws Exception {
  5. Set<String> members = GroupSessionFactory.getGroupSession()
  6. .getMembers(msg.getGroupName());
  7. ctx.writeAndFlush(new GroupMembersResponseMessage(members));
  8. }
  9. }

3.5 聊天室业务-退出

  1. @Slf4j
  2. @ChannelHandler.Sharable
  3. public class QuitHandler extends ChannelInboundHandlerAdapter {
  4. // 当连接断开时触发 inactive 事件
  5. @Override
  6. public void channelInactive(ChannelHandlerContext ctx) throws Exception {
  7. SessionFactory.getSession().unbind(ctx.channel());
  8. log.debug("{} 已经断开", ctx.channel());
  9. }
  10. // 当出现异常时触发
  11. @Override
  12. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  13. SessionFactory.getSession().unbind(ctx.channel());
  14. log.debug("{} 已经异常断开 异常是{}", ctx.channel(), cause.getMessage());
  15. }
  16. }

3.6 聊天室业务-空闲检测

连接假死

原因

  • 网络设备出现故障,例如网卡,机房等,底层的 TCP 连接已经断开了,但应用程序没有感知到,仍然占用着资源。
  • 公网网络不稳定,出现丢包。如果连续出现丢包,这时现象就是客户端数据发不出去,服务端也一直收不到数据,就这么一直耗着
  • 应用程序线程阻塞,无法进行数据读写

问题

  • 假死的连接占用的资源不能自动释放
  • 向假死的连接发送数据,得到的反馈是发送超时

服务器端解决

  • 怎么判断客户端连接是否假死呢?如果能收到客户端数据,说明没有假死。因此策略就可以定为,每隔一段时间就检查这段时间内是否接收到客户端数据,没有就可以判定为连接假死
  1. // 用来判断是不是 读空闲时间过长,或 写空闲时间过长
  2. // 5s 内如果没有收到 channel 的数据,会触发一个 IdleState#READER_IDLE 事件
  3. ch.pipeline().addLast(new IdleStateHandler(5, 0, 0));
  4. // ChannelDuplexHandler 可以同时作为入站和出站处理器
  5. ch.pipeline().addLast(new ChannelDuplexHandler() {
  6. // 用来触发特殊事件
  7. @Override
  8. public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception{
  9. IdleStateEvent event = (IdleStateEvent) evt;
  10. // 触发了读空闲事件
  11. if (event.state() == IdleState.READER_IDLE) {
  12. log.debug("已经 5s 没有读到数据了");
  13. ctx.channel().close();
  14. }
  15. }
  16. });

客户端定时心跳

  • 客户端可以定时向服务器端发送数据,只要这个时间间隔小于服务器定义的空闲检测的时间间隔,那么就能防止前面提到的误判,客户端可以定义如下心跳处理器
  1. // 用来判断是不是 读空闲时间过长,或 写空闲时间过长
  2. // 3s 内如果没有向服务器写数据,会触发一个 IdleState#WRITER_IDLE 事件
  3. ch.pipeline().addLast(new IdleStateHandler(0, 3, 0));
  4. // ChannelDuplexHandler 可以同时作为入站和出站处理器
  5. ch.pipeline().addLast(new ChannelDuplexHandler() {
  6. // 用来触发特殊事件
  7. @Override
  8. public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception{
  9. IdleStateEvent event = (IdleStateEvent) evt;
  10. // 触发了写空闲事件
  11. if (event.state() == IdleState.WRITER_IDLE) {
  12. // log.debug("3s 没有写数据了,发送一个心跳包");
  13. ctx.writeAndFlush(new PingMessage());
  14. }
  15. }
  16. });

流程总结

gitee源码链接

聊天室基础版本

相关文章