這一章繼續爲你們介紹Netty自帶的解碼器,上一章主要介紹了支持TCP粘包/分包處理的linebasedframedecoder,它是根據回車或換行符、換行符來斷定結束位置的。那麼若是咱們想本身定義分隔符,怎麼解決?這時候咱們就要藉助DelimeterBasedFrameDecoder,它支持自定義分隔符,而且支持配置單行的最大長度。這個其實不難理解,好比說咱們解析一幀,例如:你好!哈哈!你好!Netty怎麼準確知道一幀呢?從這例子來看,感嘆號!就是解析一幀的標準。這樣看來原理其實很是簡單,只是Netty替咱們處理好了,咱們只須要會用就能夠了,廢話很少說了,上代碼。java
服務端代碼:bootstrap
package com.dlb.note.server; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.DelimiterBasedFrameDecoder; import io.netty.handler.codec.string.StringDecoder; import java.nio.charset.Charset; /** * 功能:分隔符解碼器時間服務器 * 版本:1.0 * 日期:2016/12/9 16:11 * 做者:馟蘇 */ public class DelimiterFrameDecoderTimeServer { /** * main函數 * @param args */ public static void main(String []args) { // 構造nio線程組 EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workGroup = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 1024) .childHandler(new ChannelInitializer() { protected void initChannel(Channel channel) throws Exception { // 查找分隔符$_,配置單行最大長度爲1024 ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes()); channel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter)); // 將字節對象轉換爲字符串 channel.pipeline().addLast(new StringDecoder(Charset.forName("UTF-8"))); channel.pipeline().addLast(new MyDelimiterHandler()); } }); // 綁定端口,同步等待成功 ChannelFuture future = bootstrap.bind(8888).sync(); System.out.println("----服務端在8888端口監聽----"); // 等待服務端監聽端口關閉 future.channel().closeFuture().sync(); } catch (Exception e) { e.printStackTrace(); } finally { // 優雅的退出,釋放線程池資源 bossGroup.shutdownGracefully(); workGroup.shutdownGracefully(); } } } class MyDelimiterHandler extends ChannelHandlerAdapter { // 客戶端連接異常 @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { System.out.println("client exception,ip=" + ctx.channel().remoteAddress()); ctx.close(); super.exceptionCaught(ctx, cause); } // 客戶端連接到來 @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println("client come,ip=" + ctx.channel().remoteAddress()); super.channelActive(ctx); } // 客戶端連接關閉 @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { System.out.println("client close,ip=" + ctx.channel().remoteAddress()); ctx.close(); super.channelInactive(ctx); } // 可讀 @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { String req = (String) msg; System.out.println(req); super.channelRead(ctx, msg); } }