我们在网络编程中,处理粘包,半包是避免不了的问题,那今天就有一个小例子,带大家了解下netty中粘包,半包的处理方法:
题目:
客户端输入一段内容:
- hello wordn
- I‘m zhangsann
- How are you?n
变成了下面两个bytebuf
- hello wordnI’m zhangsannHo
- w are you?n
现在要求编写程序,将错乱的数据恢复到原始按n分割的数据
输入数据样例:
ByteBuffer source = ByteBuffer.allocate(32); source.put("hello wordnI'm zhangsannHo".getBytes()); split(source); source.put("w are you?n".getBytes()); split(source);
输出代码:
public class NettySpilt { public static void main(String[] args) { ByteBuffer source = ByteBuffer.allocate(32); source.put("hello wordnI'm zhangsannHo".getBytes()); split(source); source.put("w are you?n".getBytes()); split(source); } private static void split(ByteBuffer source) { //切换到读模式 source.flip(); for (int i = 0; i < source.limit(); i++) { //如果找到'n',将前面保存至target内 if (source.get(i) == 'n') { int length = i + 1 - source.position(); ByteBuffer target = ByteBuffer.allocate(length); for (int j = 0; j < length; j++) { target.put(source.get(j)); } } } source.compact(); } }