问题:网络上有多条数据发送给服务器,数据之间用 \n 进行分割,但由于某些原因这些数据在接收时被进行了重新组合,现在要求编写程序将错乱的数据恢复成原来的按 \n 分隔的数据。
例如原始数据有3条为:
Hello, world\n
I’am zhangsan\n
How are you?\n
变成了两个ByteBuffer(黏包,半包)
Hello, world\nI’am zhangsan\nHo
w are you?\n
import java.nio.ByteBuffer;
public class Main {
public static void main(String[] args) {
ByteBuffer source = ByteBuffer.allocate(32);
source.put("Hello, world\nI'am zhangsan\nHo".getBytes());
split(source);
source.put("w are you?\n".getBytes());
split(source);
}
private static void split(ByteBuffer source) {
//切换为读模式,将position指针归0
source.flip();
for (int i = 0; i< source.limit();i++){
//找到一条完整消息
if(source.get(i)=='\n'){
int len = i + 1 - source.position();
ByteBuffer target = ByteBuffer.allocate(len);
for (int j = 0; j<len; j++){
target.put(source.get());
}
//输出
System.out.println(new String(target.array()));
}
}
//将buffer没有读取到的移动到头部
source.compact();
}
}