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();
}
}