这一章继续为你们介绍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); } }