netty中的粘包、拆包解决方案
LineBasedFrameDecode+StringDecoder
LineBasedFrameDecode:遍历字节数组,遇到"\n","\r\n"以此作为结束符。可以配置单行的最大长度,超过后抛出异常。
StringDecoder:将接收到的字节转换成字符串。
initChannel(SocketChannel ch) throws Exception{
ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new CustomerHandler);
}
DelimiterBasedFrameDecoder
initChannel(SocketChannel ch) throws Exception{
ByteBuf delimiter = Upooled.copiedBuffer("$/%@^#/").getBytes();
ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new CustomerHandler);
}
FixedLengthFrameDecoder
initChannel(SocketChannel ch) throws Exception{
ch.pipeline().addLast(new FixedLengthFrameDecoder(20));
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new CustomerHandler);
}