zl程序教程

您现在的位置是:首页 >  其他

当前栏目

Netty的常用编解码器与使用

2023-03-07 09:49:02 时间

本文转载自微信公众号「源码学徒」,作者皇甫嗷嗷叫。转载本文请联系源码学徒公众号。

我们本章节将了解基本的编解码器以及自定义编解码器的使用,在了解之前,我们先看一段代码:

一、开发服务端

1.开发服务端的Handler

  1. /** 
  2.  * ********************************************************************* 
  3.  * 欢迎关注公众号: 【源码学徒】 
  4.  * ********************************************************************* 
  5.  * 
  6.  * @author huangfu 
  7.  * @date 2021/5/6 21:22 
  8.  */ 
  9. public class CodecServerHandler extends ChannelInboundHandlerAdapter { 
  10.     @Override 
  11.     public void channelActive(ChannelHandlerContext ctx) throws Exception { 
  12.         //开启一个定时任务 
  13.         ctx.channel().eventLoop().scheduleAtFixedRate(() -> { 
  14.             ByteBufAllocator aDefault = ByteBufAllocator.DEFAULT
  15.             ByteBuf byteBuf = aDefault.directBuffer(); 
  16.             //向客户端写一句话 
  17.             byteBuf.writeBytes("无论是任何的源码学习,永远都是枯燥、乏味的,他远没有写出一段很牛逼的代码有成就感!但是当你登堂入室的那一刻,你会发现,源码的阅读是如此的享受!".getBytes(StandardCharsets.UTF_8)); 
  18.             ctx.writeAndFlush(byteBuf); 
  19.         }, 10, 10, TimeUnit.MILLISECONDS); 
  20.     } 
  21.  
  22.     @Override 
  23.     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 
  24.         cause.printStackTrace(); 
  25.         super.exceptionCaught(ctx, cause); 
  26.     } 

2. 开发服务端的Server

  1. /** 
  2.  * ********************************************************************* 
  3.  * 欢迎关注公众号: 【源码学徒】 
  4.  * ********************************************************************* 
  5.  * 
  6.  * @author huangfu 
  7.  * @date 2021/5/6 21:20 
  8.  */ 
  9. public class CodecServer { 
  10.     public static void main(String[] args) throws InterruptedException { 
  11.         EventLoopGroup boss = new NioEventLoopGroup(1); 
  12.         EventLoopGroup worker = new NioEventLoopGroup(); 
  13.  
  14.         try { 
  15.             ServerBootstrap serverBootstrap = new ServerBootstrap(); 
  16.             serverBootstrap.group(boss, worker) 
  17.                     .channel(NioServerSocketChannel.class) 
  18.                     .localAddress(8989) 
  19.                     .childHandler(new ChannelInitializer<SocketChannel>() { 
  20.                         @Override 
  21.                         protected void initChannel(SocketChannel ch) throws Exception { 
  22.                             ch.pipeline().addLast("codecHandler", new CodecHandler()); 
  23.                         } 
  24.                     }); 
  25.             ChannelFuture channelFuture = serverBootstrap.bind().sync(); 
  26.             channelFuture.channel().closeFuture().sync(); 
  27.         } finally { 
  28.             boss.shutdownGracefully(); 
  29.             worker.shutdownGracefully(); 
  30.         } 
  31.     } 

二、开发客户端

1.开发客户端的Handler

  1. /** 
  2.  * ********************************************************************* 
  3.  * 欢迎关注公众号: 【源码学徒】 
  4.  * ********************************************************************* 
  5.  * 
  6.  * @author huangfu 
  7.  * @date 2021/5/6 21:31 
  8.  */ 
  9. public class CodecClientHandler extends ChannelInboundHandlerAdapter { 
  10.     @Override 
  11.     public void channelActive(ChannelHandlerContext ctx) throws Exception { 
  12.         System.out.println("连接成功"); 
  13.     } 
  14.  
  15.     @Override 
  16.     public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 
  17.         ByteBuf byteBuf = (ByteBuf) msg; 
  18.         System.out.println(byteBuf.toString(StandardCharsets.UTF_8)); 
  19.         super.channelRead(ctx, msg); 
  20.     } 

2.开发客户端

  1. /** 
  2.  * ********************************************************************* 
  3.  * 欢迎关注公众号: 【源码学徒】 
  4.  * ********************************************************************* 
  5.  * 
  6.  * @author huangfu 
  7.  * @date 2021/5/6 21:29 
  8.  */ 
  9. public class CodecClient { 
  10.     public static void main(String[] args) throws InterruptedException { 
  11.         EventLoopGroup worker = new NioEventLoopGroup(); 
  12.  
  13.         try { 
  14.             Bootstrap bootstrap = new Bootstrap(); 
  15.             bootstrap.group(worker) 
  16.                     .remoteAddress(new InetSocketAddress("127.0.0.1",8989)) 
  17.                     .channel(NioSocketChannel.class) 
  18.                     .handler(new ChannelInitializer<SocketChannel>() { 
  19.                         @Override 
  20.                         protected void initChannel(SocketChannel ch) throws Exception { 
  21.                             ch.pipeline().addLast("codecClientHandler",new CodecClientHandler()); 
  22.                         } 
  23.                     }); 
  24.  
  25.             ChannelFuture channelFuture = bootstrap.connect().sync(); 
  26.             channelFuture.channel().closeFuture().sync(); 
  27.  
  28.         }finally { 
  29.             worker.shutdownGracefully(); 
  30.         } 
  31.     } 

三、结果演示

上述的代码相信大家都极其熟悉,就是开发一个服务端和客户端,当客户端连接到服务端之后,服务端每隔10毫秒向客户端输出一句话,客户端收到之后打印出来!

预期结果:

实际结果:

我们发现,真正跑起来,却并没有按照我们预期那样逐行打印,而是好几行连在一起打印,而且有些字符还出现了乱码,这是为什么呢?

了解过网络传输的同学大概都明白,Socket其实也是TCP的一种,底层通过流的方式传输,由服务端发送的数据到客户端,客户端的Netty需要重新拼装为一个完整的包:

  • 当传输的数据量过大的时候,Netty就 分多从拼装,这就造成了乱码的现象! 这种现象,术语叫做半包
  • 当Netty读取的时候,一次读取了两个数据包,那就会自动将两个数据包合为一个数据包,从而完成封装为一个数据包,这就是造成好几行连着打印的问题! 这种现象 术语叫做粘包

 

四、常用的编解码器

为什么会发生粘包、半包!Netty在解析底层数据流转换成ByteBuf,但是当请求过于频繁的时候,两次的请求数据可能会被合并为一个,甚至,一次数据合并一个半的数据流,此时因为数据流字节的不完全接收,会导致读取数据不正确或者乱码等问题!

假设,我们预先知道了这个数据包的一个规则,当数据包规则不满足的情况下等待,超过数据规则限制的时候进行切分,那么是不是就能够有效的区分数据包的界限,从根本上上解决粘包半包的问题?

1. 基于换行符的解码器

LineBasedFrameDecoder

该代码将以\n或者\r\n 作为区分数据包的依据,程序在进行数据解码的时候,会判断该当前的数据包内是否存在\n或者\r\n,当存在的时候会截取以\n或者\r\n的一段字符,作为一个完整的数据包!

客户端增加解码器:

CodecClient:

  1. .handler(new ChannelInitializer<SocketChannel>() { 
  2.     @Override 
  3.     protected void initChannel(SocketChannel ch) throws Exception { 
  4.         //增加数据包解码器基于换行符的解码器 
  5.         ch.pipeline().addLast("lineBasedFrameDecoder", new LineBasedFrameDecoder(Integer.MAX_VALUE)); 
  6.         ch.pipeline().addLast("codecClientHandler", new CodecClientHandler()); 
  7.     } 
  8. }); 

服务端数据结构发生改变:

CodecServerHandler:

  1. ByteBuf byteBuf = aDefault.directBuffer(); 
  2. //增加一个换行符 
  3. byteBuf.writeBytes("无论是任何的源码学习,永远都是枯燥、乏味的,他远没有写出一段很牛逼的代码有成就感!但是当你登堂入室的那一刻,你会发现,源码的阅读是如此的享受!\n".getBytes(StandardCharsets.UTF_8)); 
  4. ctx.writeAndFlush(byteBuf); 

效果图:

2. 基于自定义换行符的解码器

DelimiterBasedFrameDecoder

该代码将以自定义符号作为区分数据包的依据,程序在进行数据解码的时候,会判断该当前的数据包内是否存在指定的自定义的符号,当存在的时候会截取以自定义符号为结尾的一段字符,作为一个完整的数据包!

客户端增加解码器:

CodecClient:

  1. .handler(new ChannelInitializer<SocketChannel>() { 
  2.     @Override 
  3.     protected void initChannel(SocketChannel ch) throws Exception { 
  4.         ByteBuf byteBuf = Unpooled.copiedBuffer("|".getBytes(StandardCharsets.UTF_8)); 
  5.         ch.pipeline().addLast("delimiterBasedFrameDecoder", new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, byteBuf)); 
  6.         ch.pipeline().addLast("codecClientHandler", new CodecClientHandler()); 
  7.     } 
  8. }); 

服务端数据结构发生改变:

CodecServerHandler:

  1. ByteBuf byteBuf = aDefault.directBuffer(); 
  2. //末尾增加一个指定的字符 
  3. byteBuf.writeBytes("无论是任何的源码学习,永远都是枯燥、乏味的,他远没有写出一段很牛逼的代码有成就感!但是当你登堂入室的那一刻,你会发现,源码的阅读是如此的享受!|".getBytes(StandardCharsets.UTF_8)); 
  4. ctx.writeAndFlush(byteBuf); 

效果图:

3. 基于固定长度的解码器

FixedLengthFrameDecoder

定长数据解码器适用于每次发送的数据包是一个固定长度的场景,指定每次读取的数据包的数据长度来进行解码操作!

我们查看我们的数据总共长度是多少:

  1. 无论是任何的源码学习,永远都是枯燥、乏味的,他远没有写出一段很牛逼的代码有成就感!但是当你登堂入室的那一刻,你会发现,源码的阅读是如此的享受! 

经过计算为213各字符,我们假设以后的数据都是这个,我们就可以使用固定字符串,作为区分一个完整数据包的依据:

客户端增加解码器:

CodecClient:

  1. .handler(new ChannelInitializer<SocketChannel>() { 
  2.     @Override 
  3.     protected void initChannel(SocketChannel ch) throws Exception { 
  4.         //指定一个完整数据包的长度为213个 
  5.         ch.pipeline().addLast("fixedLengthFrameDecoder", new FixedLengthFrameDecoder(213)); 
  6.         ch.pipeline().addLast("codecClientHandler", new CodecClientHandler()); 
  7.     } 
  8. }); 

服务端数据结构发生改变:

CodecServerHandler:

  1. ByteBuf byteBuf = aDefault.directBuffer(); 
  2. //发送原数据 不做任何更改 
  3. byteBuf.writeBytes("无论是任何的源码学习,永远都是枯燥、乏味的,他远没有写出一段很牛逼的代码有成就感!但是当你登堂入室的那一刻,你会发现,源码的阅读是如此的享受!".getBytes(StandardCharsets.UTF_8)); 
  4. ctx.writeAndFlush(byteBuf); 

效果图:

4. 基于不定长的解码器

LengthFieldBasedFrameDecoder

不定长长度域解码器的使用是用在我们不确定数据包的大小的场景下,这也是比较常用的一个解码器

客户端增加解码器:

CodecClient:

  1. .handler(new ChannelInitializer<SocketChannel>() { 
  2.     @Override 
  3.     protected void initChannel(SocketChannel ch) throws Exception { 
  4.         ch.pipeline().addLast("lengthFieldBasedFrameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4)); 
  5.         ch.pipeline().addLast("codecClientHandler", new CodecClientHandler()); 
  6.     } 
  7. }); 

服务端数据结构发生改变:

CodecServerHandler:

  1. ByteBuf byteBuf = aDefault.directBuffer(); 
  2. byte[] bytes = "无论是任何的源码学习,永远都是枯燥、乏味的,他远没有写出一段很牛逼的代码有成就感!但是当你登堂入室的那一刻,你会发现,源码的阅读是如此的享受!".getBytes(StandardCharsets.UTF_8); 
  3. byteBuf.writeInt(bytes.length); 
  4. byteBuf.writeBytes(bytes); 
  5. ctx.writeAndFlush(byteBuf); 

他的参数比较多,我们做几个基本的认识:

maxFrameLength:本次能接收的最大的数据长度

lengthFieldOffset:设置的长度域的偏移量,长度域在数据包的起始位置,所以偏移量为0

lengthFieldLength:长度域的长度,例子使用的是Int占4位 所以参数为4

lengthAdjustment:数据包的偏移量,计算方式=数据长度 +lengthAdjustment=数据总长度 这里数据包的总长度=lengthFieldLength ,所以不需要补充,所以参数为0

initialBytesToStrip:需要跳过的字节数,这里我们只关注真正的数据,不关注数据包的长度,所以我们把长度域跳过去,长度域为4,所以跳过4

效果图:

5. 自定义编解码器

I. ByteToMessageDecoder

需求:我们需要在解码器中就将ByteBuf解码,并转成字符串,后面直接打印

开发一个自定义的解码器:

  1. /** 
  2.  * ********************************************************************* 
  3.  * 欢迎关注公众号: 【源码学徒】 
  4.  * 自定义一个基于固定长度的解码器,当解码成功后,将数据转成字符串 
  5.  * ********************************************************************* 
  6.  * 
  7.  * @author huangfu 
  8.  * @date 2021/5/7 22:43 
  9.  */ 
  10. public class MyByteToMessageDecoder extends ByteToMessageDecoder { 
  11.     private Integer length; 
  12.  
  13.     public MessageEqualDecoder(Integer length) { 
  14.         this.length = length; 
  15.     } 
  16.  
  17.     @Override 
  18.     protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { 
  19.         //当前的可读字节数 
  20.         int readableBytes = in.readableBytes(); 
  21.         //当可读字节数超过预设数量的时候 
  22.         if(readableBytes >= length) { 
  23.             byte[] bytes = new byte[length]; 
  24.             //读取出来 
  25.             in.readBytes(bytes); 
  26.             //转换成字符串 并添加进集合中 
  27.             out.add(new String(bytes, StandardCharsets.UTF_8)); 
  28.         } 
  29.     } 

客户端处理器开发:

CodecClientHandler

  1. /** 
  2.  * ********************************************************************* 
  3.  * 欢迎关注公众号: 【源码学徒】 
  4.  * ********************************************************************* 
  5.  * 
  6.  * @author huangfu 
  7.  * @date 2021/5/6 21:31 
  8.  */ 
  9. public class CodecClientHandler extends ChannelInboundHandlerAdapter { 
  10.     @Override 
  11.     public void channelActive(ChannelHandlerContext ctx) throws Exception { 
  12.         System.out.println("连接成功"); 
  13.     } 
  14.  
  15.     @Override 
  16.     public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 
  17.         //解码器已经将数据转换成字符串了,这里直接强壮为字符串使用 
  18.         String msgStr = (String) msg; 
  19.         System.out.println(msgStr); 
  20.         super.channelRead(ctx, msg); 
  21.     } 

客户端开发:

CodecClient

  1. public class CodecClient { 
  2.     public static void main(String[] args) throws InterruptedException { 
  3.         EventLoopGroup worker = new NioEventLoopGroup(); 
  4.  
  5.         try { 
  6.             Bootstrap bootstrap = new Bootstrap(); 
  7.             bootstrap.group(worker) 
  8.                     .remoteAddress(new InetSocketAddress("127.0.0.1", 8989)) 
  9.                     .channel(NioSocketChannel.class) 
  10.                     .handler(new ChannelInitializer<SocketChannel>() { 
  11.                         @Override 
  12.                         protected void initChannel(SocketChannel ch) throws Exception { 
  13.                             //添加自定义的解码器 
  14.                             ch.pipeline().addLast("messageEqualDecoder", new MyByteToMessageDecoder(213)); 
  15.                             ch.pipeline().addLast("codecClientHandler", new CodecClientHandler()); 
  16.                         } 
  17.                     }); 
  18.  
  19.             ChannelFuture channelFuture = bootstrap.connect().sync(); 
  20.             channelFuture.channel().closeFuture().sync(); 
  21.  
  22.         } finally { 
  23.             worker.shutdownGracefully(); 
  24.         } 
  25.     } 

效果图:

II. MessageToMessageDecoder

需求:我们再上面自定义的解码器的基础上增加一个需求,要求上一个解码器解码出来的数据,在传播到客户端的时候,需用[]包裹住。

开发自定义的消息转换器(泛型为String的原因是 上一个解码器已经将其转换为了String):

  1. /** 
  2.  * 将消息用[]包裹起来 
  3.  * 
  4.  * @author huangfu 
  5.  * @date 2021年5月8日08:25:21 
  6.  */ 
  7. public class MyMessageToMessageDecoder extends MessageToMessageDecoder<String> { 
  8.     @Override 
  9.     protected void decode(ChannelHandlerContext ctx, String msg, List<Object> out) throws Exception { 
  10.         if(!StringUtil.isNullOrEmpty(msg)){ 
  11.             out.add(String.format("[%s]", msg)); 
  12.         } 
  13.     } 

客户端开发:

CodecClient

  1. /** 
  2.  * ********************************************************************* 
  3.  * 欢迎关注公众号: 【源码学徒】 
  4.  * ********************************************************************* 
  5.  * 
  6.  * @author huangfu 
  7.  * @date 2021/5/6 21:29 
  8.  */ 
  9. public class CodecClient { 
  10.     public static void main(String[] args) throws InterruptedException { 
  11.         EventLoopGroup worker = new NioEventLoopGroup(); 
  12.  
  13.         try { 
  14.             Bootstrap bootstrap = new Bootstrap(); 
  15.             bootstrap.group(worker) 
  16.                     .remoteAddress(new InetSocketAddress("127.0.0.1",8989)) 
  17.                     .channel(NioSocketChannel.class) 
  18.                     .handler(new ChannelInitializer<SocketChannel>() { 
  19.                         @Override 
  20.                         protected void initChannel(SocketChannel ch) throws Exception { 
  21.                             //添加自定义的解码器 
  22.                             ch.pipeline().addLast("messageEqualDecoder", new MyByteToMessageDecoder(213)); 
  23.                             ch.pipeline().addLast("myMessageToMessageDecoder", new MyMessageToMessageDecoder()); 
  24.                             ch.pipeline().addLast("codecClientHandler", new CodecClientHandler()); 
  25.                         } 
  26.                     }); 
  27.  
  28.             ChannelFuture channelFuture = bootstrap.connect().sync(); 
  29.             channelFuture.channel().closeFuture().sync(); 
  30.  
  31.         }finally { 
  32.             worker.shutdownGracefully(); 
  33.         } 
  34.     } 

效果图:

6. 心跳检测

我们现在假设有一个客户端与服务端,客户端与服务端进行数据交互,服务端探测到客户端5秒没有发送数据 3次以上关闭连接!

开发一个心跳服务端处理器

  1. /** 
  2.  * 心跳处理的Handler 
  3.  * 
  4.  * @author huangfu 
  5.  * @date 2021年5月8日09:03:46 
  6.  */ 
  7. public class HeartBeatServerHandler extends ChannelInboundHandlerAdapter { 
  8.  
  9.     /** 
  10.      * 读空闲次数 
  11.      */ 
  12.     private int readIdleTimes = 0; 
  13.  
  14.     @Override 
  15.     public void channelActive(ChannelHandlerContext ctx) throws Exception { 
  16.         System.out.println("客户端连接:"+ ctx.channel().remoteAddress()); 
  17.         super.channelActive(ctx); 
  18.     } 
  19.  
  20.     @Override 
  21.     public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 
  22.         ByteBuf byteBuf = (ByteBuf) msg; 
  23.         String string = byteBuf.toString(StandardCharsets.UTF_8); 
  24.         System.out.println(string); 
  25.         //有数据  次数归0 
  26.         readIdleTimes = 0; 
  27.         super.channelRead(ctx, msg); 
  28.     } 
  29.  
  30.     @Override 
  31.     public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { 
  32.         if (evt instanceof IdleStateEvent) { 
  33.             IdleStateEvent idleStateEvent = (IdleStateEvent) evt; 
  34.             if (idleStateEvent.state() == IdleState.READER_IDLE) { 
  35.                 System.out.println("发生读空闲"); 
  36.                 readIdleTimes++; 
  37.             } 
  38.             //3次读空闲之后,关闭客户端连接 
  39.             if (readIdleTimes > 3) { 
  40.                 //关闭客户端连接 
  41.                 System.out.println("客户端连接被关闭:"+ ctx.channel().remoteAddress()); 
  42.                 ctx.close(); 
  43.             } 
  44.         } 
  45.     } 

开发一个心跳服务端

  1. /** 
  2.  * 心跳服务器 
  3.  * 
  4.  * @author huangfu 
  5.  * @date 2021年5月8日08:52:56 
  6.  */ 
  7. public class HeartBeatServer { 
  8.     public static void main(String[] args) { 
  9.         EventLoopGroup boss = new NioEventLoopGroup(1); 
  10.         EventLoopGroup worker = new NioEventLoopGroup(); 
  11.  
  12.         try { 
  13.             ServerBootstrap bootstrap = new ServerBootstrap(); 
  14.             bootstrap.group(boss,worker) 
  15.                     .channel(NioServerSocketChannel.class) 
  16.                     .localAddress(8989) 
  17.                     .childHandler(new ChannelInitializer<SocketChannel>() { 
  18.                         @Override 
  19.                         protected void initChannel(SocketChannel ch) throws Exception { 
  20.                             //心跳触发器  读空闲  写空闲  读写空闲5秒的均会触发心跳事件 
  21.                             ch.pipeline().addLast(new IdleStateHandler(5,5,5, TimeUnit.SECONDS)); 
  22.                             ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0,4,0,4)); 
  23.                             //定义处理器 
  24.                             ch.pipeline().addLast(new HeartBeatServerHandler()); 
  25.                         } 
  26.                     }); 
  27.             ChannelFuture channelFuture = bootstrap.bind().sync(); 
  28.             channelFuture.channel().closeFuture().sync(); 
  29.         } catch (InterruptedException e) { 
  30.             e.printStackTrace(); 
  31.         } finally { 
  32.             boss.shutdownGracefully(); 
  33.             worker.shutdownGracefully(); 
  34.         } 
  35.  
  36.     } 

开发一个心跳客户端处理器

  1. /** 
  2.  * 客户端心跳处理 
  3.  * 
  4.  * @author huangfu 
  5.  * @date 2021年5月8日09:29:05 
  6.  */ 
  7. public class HeartBeatClientHandler extends ChannelInboundHandlerAdapter { 
  8.  
  9.     @Override 
  10.     public void channelActive(ChannelHandlerContext ctx) throws Exception { 
  11.         System.out.println("通道被激活"); 
  12.         super.channelActive(ctx); 
  13.     } 
  14.  
  15.     @Override 
  16.     public void channelInactive(ChannelHandlerContext ctx) throws Exception { 
  17.         System.out.println("通道被销毁"); 
  18.         super.channelInactive(ctx); 
  19.     } 

开发一个心跳客户端

  1. /** 
  2.  * 心跳消息服务 
  3.  * 
  4.  * @author huangfu 
  5.  * @date 2021年5月8日09:37:07 
  6.  */ 
  7. public class HeartBeatClient { 
  8.     private static Channel channel = null
  9.     private static Scanner sc = new Scanner(System.in); 
  10.     public static void main(String[] args) { 
  11.         EventLoopGroup worker = new NioEventLoopGroup(); 
  12.         try { 
  13.             Bootstrap bootstrap = new Bootstrap(); 
  14.             bootstrap.group(worker) 
  15.                     .channel(NioSocketChannel.class) 
  16.                     .remoteAddress("127.0.0.1",8989) 
  17.                     .handler(new ChannelInitializer<SocketChannel>() { 
  18.                         @Override 
  19.                         protected void initChannel(SocketChannel ch) throws Exception { 
  20.                             //长度解码器 
  21.                             ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0,4,0,4)); 
  22.                             ch.pipeline().addLast(new HeartBeatClientHandler()); 
  23.                         } 
  24.                     }); 
  25.             //连接服务端 
  26.             ChannelFuture channelFuture = bootstrap.connect().sync(); 
  27.             channel = channelFuture.channel(); 
  28.             Thread thread = new Thread(HeartBeatClient::writeStr); 
  29.             thread.setDaemon(true); 
  30.             thread.start(); 
  31.             channel.closeFuture().sync(); 
  32.         } catch (InterruptedException e) { 
  33.             e.printStackTrace(); 
  34.         } finally { 
  35.             worker.shutdownGracefully(); 
  36.         } 
  37.     } 
  38.  
  39.     /** 
  40.      * 向服务端写入数据 
  41.      */ 
  42.     public static void writeStr(){ 
  43.         while (true) { 
  44.             System.out.print("请输入要发送的数据:"); 
  45.             //从键盘读入数据 
  46.             String line = sc.nextLine(); 
  47.             ByteBuf buffer = Unpooled.buffer(); 
  48.             buffer.writeInt(line.length()); 
  49.             buffer.writeBytes(line.getBytes(StandardCharsets.UTF_8)); 
  50.             //发送数据 
  51.             channel.writeAndFlush(buffer).addListener(future -> { 
  52.                 if (future.isSuccess()) { 
  53.                     System.out.println("发送成功"); 
  54.                 } 
  55.             }); 
  56.         } 
  57.  
  58.     }