由于咱们在进行服务端开发过程当中,必定会遇到TCP的粘包和分包问题,所谓粘包和分包就是由于TCP的滑动窗口以及拥塞避免等机制形成的,好比说我发一个包并非一次性发完,可能拆成多个包屡次发送,当我接收一个包时,可能会接收两个包的组合体。那么对于这种问题,Netty框架是如何解决的呢?这里,我先接收一个Netty给咱们提供的能够解决粘包和分包问题的解码器LineBasedFrameDecoder,它的主要原理是这样的:遍历bytebuf中的可读字节,将\n和\r\n断定为结束位置。java
接下来让我看一下服务端的例子:bootstrap
其中LineBasedFrameDecoder已经介绍了,而StringDecoder则能够将字节自动转换为子串。服务器
package com.dlb.note.server; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.LineBasedFrameDecoder; import io.netty.handler.codec.string.StringDecoder; import java.nio.charset.Charset; /** * 功能:支持tcp粘包/拆包的回车/换行符服务器 * 版本:1.0 * 日期:2016/12/9 15:21 * 做者:馟苏 */ public class LineBasedFrameDecoderTimeServer { /** * 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 { // 遍历bytebuf中的可读字节,将\n和\r\n断定为结束位置,配置单行最大长度为1024 channel.pipeline().addLast(new LineBasedFrameDecoder(1024)); // 将字节对象转换为字符串 channel.pipeline().addLast(new StringDecoder(Charset.forName("UTF-8"))); channel.pipeline().addLast(new MyHandler()); } }); // 绑定端口,同步等待成功 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 MyHandler 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); } }