成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

Netty的常用編解碼器與使用

開發 前端
我們發現,真正跑起來,卻并沒有按照我們預期那樣逐行打印,而是好幾行連在一起打印,而且有些字符還出現了亂碼,這是為什么呢?

[[414980]]

本文轉載自微信公眾號「源碼學徒」,作者皇甫嗷嗷叫。轉載本文請聯系源碼學徒公眾號。

我們本章節將了解基本的編解碼器以及自定義編解碼器的使用,在了解之前,我們先看一段代碼:

一、開發服務端

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.     } 

 

責任編輯:武曉燕 來源: 源碼學徒
相關推薦

2021-10-08 09:38:57

NettyChannelHand架構

2021-04-07 13:52:57

GoogleLyra編譯器

2025-04-10 10:15:30

2024-07-05 08:27:07

2022-10-10 10:38:22

FedoraopenSUSE視頻編解碼

2020-02-19 19:15:27

UbuntuLinux媒體編解碼器

2020-12-22 07:58:46

Netty編碼器解碼器

2022-02-15 21:42:23

嵌入式系統音頻編解碼器開發

2023-06-20 08:34:33

SVT-AV1開源

2021-12-25 16:20:38

微軟WindowsWindows 10

2021-08-18 10:41:24

GoogleSoundStream神經網絡

2023-07-26 16:31:09

Windows 10Windows 11微軟

2021-04-22 11:21:03

Windows 10Windows微軟

2024-02-28 08:22:07

2021-10-08 10:50:33

AI 編碼器人工智能

2020-10-10 15:22:33

Windows 功能系統

2023-07-05 11:16:59

2021-08-20 13:12:18

Google 開源技術

2021-08-11 10:03:07

iOS 14.8蘋果iOS 15
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 久久高清精品 | 成人精品免费视频 | 久久国产精品99久久久久久丝袜 | 精品欧美一区二区精品久久久 | 欧美亚洲成人网 | 欧美精品首页 | 中文字幕亚洲精品 | 日韩视频一区在线观看 | 91精品国产综合久久久久久蜜臀 | 先锋资源在线 | 国产在线观看一区二区 | 福利二区| 欧美炮房 | 国产一区二区三区久久久久久久久 | 一区二区三区视频在线观看 | 一区二区三区免费观看 | 国产精品欧美一区喷水 | 国产一二区视频 | 亚洲成av人影片在线观看 | 91精品国产综合久久久久久首页 | 日韩欧美三区 | 国产精品乱码一区二三区小蝌蚪 | 日韩精品国产精品 | 二区中文| 视频一区欧美 | 成人欧美一区二区三区黑人孕妇 | 国产精品视频久久久 | 久草在线 | www.久| 日本三级做a全过程在线观看 | 久久精品亚洲精品 | 国产精品美女一区二区 | 五月香婷婷 | 一级大黄色片 | 99热都是精品 | 国产欧美在线 | 日本久久综合网 | 久久另类视频 | 亚洲欧美一区二区三区国产精品 | 日韩av成人在线 | 国产一区精品 |