什么是半包和粘包?
半包问题
半包问题是指一个完整的应用层消息被分成多个 tcp 数据包发送,接收端在一次读取操作中只接收到消息的一部分。
例如,发送端发送了一条 100 字节的消息,但由于网络原因,这条消息被拆分成了两个 tcp 数据包,一个 60 字节,另一个 40 字节。接收端可能在第一次读取时只接收到前 60 字节的数据,剩下的 40 字节需要在后续的读取操作中才能接收到。
粘包问题
粘包问题是指多个应用层消息在传输过程中被粘在一起,接收端在一次读取操作中接收到大于 1个消息的情况。
例如,发送端发送了两条消息,每条 50 字节,但接收端在一次读取操作中收到了 80 字节的数据,超过了 1条消息的内容。
产生原因
产生半包和粘包问题主要是以下 3个原因:
- tcp 的流式特性:tcp 是面向字节流的协议,没有消息边界的概念,它保证数据的顺序和可靠性,但不保证每次发送的数据对应每次接收的数据。
- 网络状况:网络的拥塞、延迟、抖动等因素可能导致数据包的拆分和重组。
- 操作系统和缓冲区:操作系统 tcp/ip 协议栈和应用程序的缓冲区大小也会影响数据的读取方式。
示例
假设发送端发送了两条消息:
- 消息1:hello
- 消息2:world
在半包情况下,接收端可能会这样接收:
- 第一次读取:hel
- 第二次读取:lowo
- 第三次读取:rld
在粘包情况下,接收端可能会这样接收:
- 第一次读取:hellowor
- 第二次读取:ld
解决方案
基于固定长度的解码器
基于固定长度的解码器是指发消息时,每条消息的长度固定,读消息时也通过固定长度来读取消息,从而解决半包和粘包问题。
实现方式
netty 提供了 fixedlengthframedecoder 类来实现这一功能,核心源码如下:
public class fixedlengthframedecoder extends bytetomessagedecoder { private final int framelength; public fixedlengthframedecoder(int framelength) { this.framelength = framelength; } @override protected void decode(channelhandlercontext ctx, bytebuf in, list<object> out) throws exception { while (in.readablebytes() >= framelength) { bytebuf buf = in.readbytes(framelength); out.add(buf); } } }
注意点
使用定长帧需要注意以下几点:
- 固定长度:消息长度必须是固定的,发送端需要确保消息长度一致。如果长度超出固定长度,解包时消息就会错位,如果消息不足固定长度,需要使用填充字符补齐。
- 填充字符:选择合适的填充字符(如空格)来补齐消息长度,接收端在处理时需要去除这些填充字符。
优点
- 简单易实现:实现起来非常简单,不需要额外的头部信息或分隔符。
- 解析效率高:由于每个消息长度固定,接收端解析时只需按照固定长度读取。
缺点
- 不灵活:消息长度固定,可能会造成空间浪费(如果消息长度较短)或不足(如果消息长度较长)。
- 适用场景有限:适用于固定格式和长度的协议,不适用于可变长度消息的场景。
示例
下面我们通过一个示例来展示使用定长帧是如何解决半包粘包问题的。
发送端,确保每个消息的长度固定。如果实际消息长度不足,可以使用填充字符(如空格)来补齐。
public class fixedlengthframesender { private static final int frame_length = 10; // 固定消息长度 public static void send(channel channel, string message) { // 确保消息长度不超过固定长度 if (message.length() > frame_length) { throw new illegalargumentexception("message too long"); } // 使用空格填充消息到固定长度 string paddedmessage = string.format("%-" + frame_length + "s", message); // 将消息转换为字节数组并发送 bytebuf buffer = unpooled.copiedbuffer(paddedmessage.getbytes()); channel.writeandflush(buffer); } }
接收端,使用 netty 提供的 fixedlengthframedecoder 解码器来处理固定长度的消息。
import io.netty.channel.channelhandlercontext; import io.netty.channel.channelinboundhandleradapter; import io.netty.handler.codec.fixedlengthframedecoder; import io.netty.channel.channelinitializer; import io.netty.channel.channelpipeline; import io.netty.channel.socket.socketchannel; import io.netty.bootstrap.serverbootstrap; import io.netty.channel.nio.nioeventloopgroup; import io.netty.channel.socket.nio.nioserversocketchannel; public class fixedlengthframereceiver { private static final int frame_length = 10; // 固定消息长度 public static void main(string[] args) throws exception { nioeventloopgroup bossgroup = new nioeventloopgroup(1); nioeventloopgroup workergroup = new nioeventloopgroup(); try { serverbootstrap b = new serverbootstrap(); b.group(bossgroup, workergroup) .channel(nioserversocketchannel.class) .childhandler(new channelinitializer<socketchannel>() { @override public void initchannel(socketchannel ch) throws exception { channelpipeline p = ch.pipeline(); // 添加定长帧解码器 p.addlast(new fixedlengthframedecoder(frame_length)); // 添加自定义处理器 p.addlast(new fixedlengthframehandler()); } }); // 启动服务器 b.bind(8888).sync().channel().closefuture().sync(); } finally { bossgroup.shutdowngracefully(); workergroup.shutdowngracefully(); } } public static class fixedlengthframehandler extends channelinboundhandleradapter { @override public void channelread(channelhandlercontext ctx, object msg) { bytebuf in = (bytebuf) msg; byte[] receivedbytes = new byte[in.readablebytes()]; in.readbytes(receivedbytes); string receivedmsg = new string(receivedbytes).trim(); // 去除填充字符 system.out.println("received: " + receivedmsg); } @override public void exceptioncaught(channelhandlercontext ctx, throwable cause) { cause.printstacktrace(); ctx.close(); } } }
基于换行符解码器
自定义分隔符解码器
基于换行符解码器和自定义分隔符解码器(比如 特殊字符)来划分消息边界,从而解决半包和粘包问题,使用者可以根据自己的需求灵活确定分隔符。
实现方式
netty 提供了 delimiterbasedframedecoder 类来实现这一功能,核心源码如下:
public delimiterbasedframedecoder( int maxframelength, boolean stripdelimiter, boolean failfast, bytebuf... delimiters) { validatemaxframelength(maxframelength); objectutil.checknonempty(delimiters, "delimiters"); if (islinebased(delimiters) && !issubclass()) { linebaseddecoder = new linebasedframedecoder(maxframelength, stripdelimiter, failfast); this.delimiters = null; } else { this.delimiters = new bytebuf[delimiters.length]; for (int i = 0; i < delimiters.length; i ++) { bytebuf d = delimiters[i]; validatedelimiter(d); this.delimiters[i] = d.slice(d.readerindex(), d.readablebytes()); } linebaseddecoder = null; } this.maxframelength = maxframelength; this.stripdelimiter = stripdelimiter; this.failfast = failfast; }
注意点
- 分隔符选择:选择一个不会出现在消息内容中的分隔符(如换行符 \n 或特定字符 |)。
- 消息格式:发送端在每个消息的末尾添加分隔符,确保接收端能够正确解析消息边界。
优点
- 灵活性高:可以处理可变长度的消息。
- 实现相对简单:只需在消息末尾添加特定的分隔符,接收端根据分隔符拆分消息。
缺点
- 分隔符冲突:如果消息内容中包含分隔符,可能导致解析错误,需要对消息内容进行转义处理。
- 解析效率低:需要扫描整个数据流寻找分隔符,效率较低。
示例
下面我们通过一个示例来展示使用分隔符是如何解决半包粘包问题的。
发送端,确保每个消息以特定的分隔符结尾。常用的分隔符包括换行符(\n)、特定字符(如 |)等。
public class delimiterbasedframesender { private static final string delimiter = "\n"; // 分隔符 public static void send(channel channel, string message) { // 在消息末尾添加分隔符 string delimitedmessage = message + delimiter; // 将消息转换为字节数组并发送 bytebuf buffer = unpooled.copiedbuffer(delimitedmessage.getbytes()); channel.writeandflush(buffer); } }
接收端,使用 netty 提供的 delimiterbasedframedecoder 解码器来处理以分隔符结尾的消息。
import io.netty.bootstrap.serverbootstrap; import io.netty.buffer.bytebuf; import io.netty.buffer.unpooled; import io.netty.channel.channelhandlercontext; import io.netty.channel.channelinboundhandleradapter; import io.netty.channel.channelinitializer; import io.netty.channel.channelpipeline; import io.netty.channel.nio.nioeventloopgroup; import io.netty.channel.socket.socketchannel; import io.netty.channel.socket.nio.nioserversocketchannel; import io.netty.handler.codec.delimiterbasedframedecoder; import io.netty.handler.codec.string.stringdecoder; public class delimiterbasedframereceiver { private static final string delimiter = "\n"; // 分隔符 private static final int max_frame_length = 1024; // 最大帧长度 public static void main(string[] args) throws exception { nioeventloopgroup bossgroup = new nioeventloopgroup(1); nioeventloopgroup workergroup = new nioeventloopgroup(); try { serverbootstrap b = new serverbootstrap(); b.group(bossgroup, workergroup) .channel(nioserversocketchannel.class) .childhandler(new channelinitializer<socketchannel>() { @override public void initchannel(socketchannel ch) throws exception { channelpipeline p = ch.pipeline(); // 添加分隔符解码器 bytebuf delimiter = unpooled.copiedbuffer(delimiter.getbytes()); p.addlast(new delimiterbasedframedecoder(max_frame_length, delimiter)); // 添加字符串解码器 p.addlast(new stringdecoder()); // 添加自定义处理器 p.addlast(new delimiterbasedframehandler()); } }); // 启动服务器 b.bind(8888).sync().channel().closefuture().sync(); } finally { bossgroup.shutdowngracefully(); workergroup.shutdowngracefully(); } } public static class delimiterbasedframehandler extends channelinboundhandleradapter { @override public void channelread(channelhandlercontext ctx, object msg) { string receivedmsg = (string) msg; system.out.println("received: " + receivedmsg); } @override public void exceptioncaught(channelhandlercontext ctx, throwable cause) { cause.printstacktrace(); ctx.close(); } } }
基于长度字段的解码器
基于长度字段的解码器是指在消息头部添加长度字段,指示消息的总长度。
实现方式
netty 提供了 lengthfieldbasedframedecoder 类来实现这一功能,核心源码如下:
public class lengthfieldbasedframedecoder extends bytetomessagedecoder { private final int maxframelength; private final int lengthfieldoffset; private final int lengthfieldlength; public lengthfieldbasedframedecoder(int maxframelength, int lengthfieldoffset, int lengthfieldlength) { this.maxframelength = maxframelength; this.lengthfieldoffset = lengthfieldoffset; this.lengthfieldlength = lengthfieldlength; } @override protected void decode(channelhandlercontext ctx, bytebuf in, list<object> out) throws exception { if (in.readablebytes() < lengthfieldoffset + lengthfieldlength) { return; } in.markreaderindex(); int length = in.getint(in.readerindex() + lengthfieldoffset); if (in.readablebytes() < lengthfieldoffset + lengthfieldlength + length) { in.resetreaderindex(); return; } in.skipbytes(lengthfieldoffset + lengthfieldlength); bytebuf frame = in.readbytes(length); out.add(frame); } }
关键点
- 长度字段位置:长度字段通常位于消息的头部,用于指示消息的总长度。
- 解码器参数:
- maxframelength:消息的最大长度,防止内存溢出。
- lengthfieldoffset:长度字段在消息中的偏移量。
- lengthfieldlength:长度字段的字节数(通常为 4 字节)。
- lengthadjustment:长度调整值,如果长度字段不包含消息头的长度,需要进行调整。
- initialbytestostrip:解码后跳过的字节数,通常为长度字段的长度。
优点
- 灵活性高:支持可变长度的消息。
- 解析效率高:通过长度字段可以直接读取完整消息,无需扫描整个数据流。
缺点
- 实现复杂:需要在消息头部添加长度字段,接收端需要解析头部信息。
- 额外开销:消息头部的长度字段会增加一些额外的字节数。
示例
下面我们通过一个示例来展示使用长度字段是如何解决半包粘包问题的。
发送端,确保每个消息在发送前都包含长度字段。长度字段通常放在消息的头部,用于指示消息的总长度。
import io.netty.buffer.bytebuf; import io.netty.buffer.unpooled; import io.netty.channel.channel; public class lengthfieldbasedframesender { public static void send(channel channel, string message) { // 将消息转换为字节数组 byte[] messagebytes = message.getbytes(); int messagelength = messagebytes.length; // 创建一个 bytebuf 来存储长度字段和消息内容 bytebuf buffer = unpooled.buffer(4 + messagelength); // 写入长度字段(4 字节,表示消息长度) buffer.writeint(messagelength); // 写入消息内容 buffer.writebytes(messagebytes); // 发送消息 channel.writeandflush(buffer); } }
接收端,使用 netty 提供的 lengthfieldbasedframedecoder 解码器来处理包含长度字段的消息。
import io.netty.bootstrap.serverbootstrap; import io.netty.buffer.bytebuf; import io.netty.channel.channelhandlercontext; import io.netty.channel.channelinboundhandleradapter; import io.netty.channel.channelinitializer; import io.netty.channel.channelpipeline; import io.netty.channel.nio.nioeventloopgroup; import io.netty.channel.socket.socketchannel; import io.netty.channel.socket.nio.nioserversocketchannel; import io.netty.handler.codec.lengthfieldbasedframedecoder; import io.netty.handler.codec.string.stringdecoder; public class lengthfieldbasedframereceiver { private static final int max_frame_length = 1024; // 最大帧长度 public static void main(string[] args) throws exception { nioeventloopgroup bossgroup = new nioeventloopgroup(1); nioeventloopgroup workergroup = new nioeventloopgroup(); try { serverbootstrap b = new serverbootstrap(); b.group(bossgroup, workergroup) .channel(nioserversocketchannel.class) .childhandler(new channelinitializer<socketchannel>() { @override public void initchannel(socketchannel ch) throws exception { channelpipeline p = ch.pipeline(); // 添加长度字段解码器 p.addlast(new lengthfieldbasedframedecoder( max_frame_length, 0, 4, 0, 4)); // 添加字符串解码器 p.addlast(new stringdecoder()); // 添加自定义处理器 p.addlast(new lengthfieldbasedframehandler()); } }); // 启动服务器 b.bind(8888).sync().channel().closefuture().sync(); } finally { bossgroup.shutdowngracefully(); workergroup.shutdowngracefully(); } } public static class lengthfieldbasedframehandler extends channelinboundhandleradapter { @override public void channelread(channelhandlercontext ctx, object msg) { string receivedmsg = (string) msg; system.out.println("received: " + receivedmsg); } @override public void exceptioncaught(channelhandlercontext ctx, throwable cause) { cause.printstacktrace(); ctx.close(); } } }
自定义解码器
如果上述 netty提供的方案无法满足业务需求的话,netty还提供了一个扩展点,使用者可以通过自定义解码器来处理消息,
实现方式
例如,自定义头部信息来表示消息长度或结束标志,示例代码如下:
public class customprotocoldecoder extends bytetomessagedecoder { @override protected void decode(channelhandlercontext ctx, bytebuf in, list<object> out) throws exception { // 根据自定义协议解析消息 if (in.readablebytes() < 4) { return; } in.markreaderindex(); int length = in.readint(); if (in.readablebytes() < length) { in.resetreaderindex(); return; } bytebuf frame = in.readbytes(length); out.add(frame); } }
优点
- 高度灵活:可以根据具体需求设计协议,适应各种复杂场景。
- 功能丰富:可以在自定义协议中添加其他信息(如校验和、序列号等),增强协议的功能和可靠性。
缺点
- 实现复杂:设计和实现自定义协议需要更多的工作量。
- 维护成本高:自定义协议可能需要更多的维护和更新工作。
总结
本文我们分析了产生半包和粘包的原因以及在netty中的 5种解决方案:
- 基于固定长度解码器
- 基于换行符解码器
- 自定义分隔符解码器
- 基于长度字段解码器
- 自定义解码器
通过学习这些内容,我们不仅掌握了半包和粘包问题的理论知识,同时学会了多种解决方法的具体实现。
以上就是netty解决半包和粘包问题的方案的详细内容,更多关于netty解决半包和粘包的资料请关注代码网其它相关文章!
发表评论