现在的位置: 首页 > 编程语言 > 正文

使用Netty解决TCP粘包和拆包问题过程详解

2020年02月14日 编程语言 ⁄ 共 5199字 ⁄ 字号 评论关闭

前言

上一篇我们介绍了如果使用Netty来开发一个简单的服务端和客户端,接下来我们来讨论如何使用解码器来解决TCP的粘包和拆包问题

TCP为什么会粘包/拆包

我们知道,TCP是以一种流的方式来进行网络转播的,当tcp三次握手简历通信后,客户端服务端之间就建立了一种通讯管道,我们可以想象成自来水管道,流出来的水是连城一片的,是没有分界线的。

TCP底层并不了解上层的业务数据的具体含义,它会根据TCP缓冲区的实际情况进行包的划分。

所以对于我们应用层而言。我们直观是发送一个个连续完整TCP数据包的,而在底层就可能会出现将一个完整的TCP拆分成多个包发送或者将多个包封装成一个大的数据包发送。

这就是所谓的TCP粘包和拆包。

当发生TCP粘包/拆包会发生什么情况

我们举一个简单例子说明:

客户端向服务端发送两个数据包:第一个内容为 123;第二个内容为456。服务端接受一个数据并做相应的业务处理(这里就是打印接受数据加一个逗号)。

那么服务端输出结果将会出现下面四种情况

服务端响应结果 结论

123,456, 正常接收,没有发生粘包和拆包 123456, 异常接收,发生tcp粘包 123,4,56, 异常接收,发生tcp拆包 12,3456, 异常接收,发生tcp拆包和粘包

如何解决

主流的协议解决方案可以归纳如下:

    消息定长,例如每个报文的大小固定为20个字节,如果不够,空位补空格; 在包尾增加回车换行符进行切割; 将消息分为消息头和消息体,消息头中包含表示消息总长度的字段; 更复杂的应用层协议。

对于之前描述的案例,在这里我们就可以采取方案1和方案3。

以方案1为例:我们每次发送的TCP包只有三个数字,那么我将报文设置为3个字节大小的,此时,服务器就会以三个字节为基准来接受包,以此来解决站包拆包问题。

Netty的解决之道

LineBasedFrameDecoder

废话不多说直接上代码

服务端

public class PrintServer { public void bind(int port) throws Exception { // 配置服务端的NIO线程组 EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 1024) .childHandler(new ChildChannelHandler()); // 绑定端口,同步等待成功 ChannelFuture f = b.bind(port).sync(); // 等待服务端监听端口关闭 f.channel().closeFuture().sync(); } finally { // 优雅退出,释放线程池资源 bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } private class ChildChannelHandler extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel arg0) throws Exception { arg0.pipeline().addLast(new LineBasedFrameDecoder(1024)); //1 arg0.pipeline().addLast(new StringDecoder()); //2 arg0.pipeline().addLast(new PrintServerHandler()); } } public static void main(String[] args) throws Exception { int port = 8080; new TimeServer().bind(port); }}

服务端Handler

public class PrintServerHandler extends ChannelHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg; byte[] req = new byte[buf.readableBytes()]; buf.readBytes(req); //将缓存区的字节数组复制到新建的req数组中 String body = new String(req, "UTF-8"); System.out.println(body); String response= "打印成功"; ByteBuf resp = Unpooled.copiedBuffer(response.getBytes()); ctx.write(resp); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { ctx.close(); }}

客户端

public class PrintClient { public void connect(int port, String host) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( new LineBasedFrameDecoder(1024)); //3 ch.pipeline().addLast(new StringDecoder()); //4 ch.pipeline().addLast(new PrintClientHandler()); } }); ChannelFuture f = b.connect(host, port).sync(); f.channel().closeFuture().sync(); } finally { // 优雅退出,释放NIO线程组 group.shutdownGracefully(); } } /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { int port = 8080; new TimeClient().connect(port, "127.0.0.1"); }}

客户端的Handler

public class PrintClientHandler extends ChannelHandlerAdapter { private static final Logger logger = Logger .getLogger(TimeClientHandler.class.getName()); private final ByteBuf firstMessage; /** * Creates a client-side handler. */ public TimeClientHandler() { byte[] req = "你好服务端".getBytes(); firstMessage = Unpooled.buffer(req.length); firstMessage.writeBytes(req); } @Override public void channelActive(ChannelHandlerContext ctx) { ctx.writeAndFlush(firstMessage); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg; byte[] req = new byte[buf.readableBytes()]; buf.readBytes(req); String body = new String(req, "UTF-8"); System.out.println("服务端回应消息 : " + body); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // 释放资源 System.out.println("Unexpected exception from downstream : " + cause.getMessage()); ctx.close(); }}

上诉代码逻辑与上一章代码逻辑相同,客户端接受服务端数据答应,并回复客户端信息,客户端接受到数据后打印数据。

我们观察代码可以发现,要想Netty解决粘包拆包问题,只需在编写服务端和客户端的pipeline上加上相应的解码器即可,上诉注释 1,2,3,4处。其余代码无需做任何修改。

LineBasedFrameDecoder+StringDecoder的组合就是按行切换的文本解码器,它被设计用来支持TCP的粘包和拆包。原理为:如果连续读取到最大长度后任然没有发现换行符,就会抛出异常,同时忽略掉之前督导的异常码流。

DelimiteBasedFrameDecoder

该解码器的可以自动完成以分割符作为码流结束标识的消息解码。(其实上一个解码器类似,如果指定分隔符为换行符,那么与上一个编码器的作用基本相同)

使用也很简单:

只需要修改服务端和客户端对应代码中的initChannel代码即可

public void initChannel(SocketChannel ch) ByteBuf delimiter = Unpooled.copiedBuffer("_".getBytes()); //1 ch.pipeline().addLast( new DelimiterBasedFrameDecoder(1024, delimiter)); //2 ch.pipeline().addLast(new StringDecoder()); //3 ch.pipeline().addLast(new PrintHandler()); }

注释1:首先创建分隔符缓冲对象ByteBuf,并指定以"_"作为分隔符。

注释2:将分隔符缓冲对象ByteBuf传入DelimiterBasedFrameDecoder,并指定最大长度。

注释3:指定为字符串字节流

FixedLengthFrameDecoder

该解码器为固定长度解码器,它能够按照指定的长度对详细进行自动解码。

使用同样也很简单:

同样只需要修改服务端和客户端对应代码中的initChannel代码即可

public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new FixedLengthFrameDecoder(20)); ch.pipeline().addLast(new StringDecoder()); ch.pipeline().addLast(new PrintHandler()); } });

这样我们就指定了,每接收20个字符大小的字符串字节流就将其看作一个包来经行处理。

总结

Netty已经在底层为我们做了很多事情,我们只需要简单的使用其提供好的解码器使用即可,源码内容待我研究归来,再进行展开,哈哈,完活~睡觉!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

本文标题: 使用Netty解决TCP粘包和拆包问题过程详解

以上就上有关使用Netty解决TCP粘包和拆包问题过程详解的相关介绍,要了解更多netty,tcp,粘包,拆包,问题内容请登录学步园。

抱歉!评论已关闭.