问题1:LengthFieldBasedFrameDecoder解码失败,再次尝试解码
如果无需再次尝试解码,可以在抛错时调用, in.resetReaderIndex();
public class TcpMessageDecoderHandler extends LengthFieldBasedFrameDecoder {private static final Logger logger = LoggerFactory.getLogger(TcpHandleServiceImpl.class);public TcpMessageDecoderHandler(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip) {super(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip);}@Overrideprotected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {try {String cmdPayload = null;// JSON内容byte[] cmdLenBytes = new byte[2]; //JSON命令长度 两个字节in.readBytes(cmdLenBytes);int cmdLen = mergeByte2Hex(cmdLenBytes[0], cmdLenBytes[1]);if (in.readableBytes() >= cmdLen) {byte[] cmdPayloadBytes = new byte[cmdLen];in.readBytes(cmdPayloadBytes); // 从输入流中读取JSON内容cmdPayload = new String(cmdPayloadBytes, StandardCharsets.UTF_8); // 转换为字符串}// 字节数据byte[] dataLenBytes = new byte[2]; //字节数据长度 两个字节if (in.readableBytes() >= 2) {in.readBytes(dataLenBytes);} else {return new TcpMessage(cmdPayload);}int dataLen = mergeByte2Hex(dataLenBytes[0], dataLenBytes[1]);byte[] dataPayloadBytes = new byte[0];if (in.readableBytes() >= dataLen) {dataPayloadBytes = new byte[dataLen];in.readBytes(dataPayloadBytes);}return new TcpMessage(cmdPayload, dataPayloadBytes);} catch (Exception e){logger.error("读取字节流出错:" + e.getMessage());// 重置读指针in.resetReaderIndex();return null;}}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {logger.error("error:" + cause.getMessage());}/*** 大端格式来读取数据,即先读取高位字节再读取低位字节。* @param high* @param low* @return*/private static int mergeByte2Hex(byte high, byte low) {return ((high & 0xFF) << 8) | (low & 0xFF);}
}