本质是因为 TCP 是流式协议,消息无边界
这里给出第4种最优的解决方法:
LengthFieldBasedFrameDecoder的四个参数分别表示:
public static void main(String[] args) {
// 最大长度,长度偏移,长度占用字节,长度调整,剥离字节数
EmbeddedChannel ch = new EmbeddedChannel(
new LengthFieldBasedFrameDecoder(1024, 0, 4,
1,5),
new LoggingHandler(LogLevel.DEBUG)
);
ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
send(buffer, "hello world");
send(buffer, "Hi!");
ch.writeOneInbound(buffer);
}
private static void send(ByteBuf buffer, String content) {
byte[] bytes = content.getBytes();
buffer.writeInt(bytes.length);
buffer.writeByte(1);
buffer.writeBytes(bytes);
}