1. \n 作为分割符,进行行的区分。
2. compact进行处理,把第一次没有读取完的数据,向前移动和后面的内容进行整合。
读取的一行的数据中 \n 后不是完整的叫粘包
读取一行数据 /n 之前不是完整的数据叫半包
//1. 半包 粘包
public class TestNIO10 {
public static void main(String[] args) {
ByteBuffer buffer = ByteBuffer.allocate(50);
buffer.put("Hi sunshuai\nl love y".getBytes());
doLineSplit(buffer);
buffer.put("ou\nDo you like me?\n".getBytes());
doLineSplit(buffer);
}
// ByteBuffer接受的数据 \n
private static void doLineSplit(ByteBuffer buffer) {
buffer.flip();
for (int i = 0; i < buffer.limit(); i++) {
if (buffer.get(i) == '\n') {
int length = i + 1 - buffer.position();
ByteBuffer target = ByteBuffer.allocate(length);
for (int j = 0; j < length; j++) {
target.put(buffer.get());
}
//截取工作完成
target.flip();
System.out.println("StandardCharsets.UTF_8.decode(target).toString() = " + StandardCharsets.UTF_8.decode(target).toString());
}
}
buffer.compact();
}
}