为什么我的一个消息混乱时使用netty?

时间:2016-11-16 10:23:31

标签: netty

我使用netty 4.1.4.Final
我的信息是这样的:
〜1234567890 ... AAAA〜
用'〜'来分割它 日志:
2016-11-16 16:09:44.213 - 1,HashCode = -1614800617,S1 = 25,S2 = -1,长度= 26
2016-11-16 16:09:44.251 - 1,HashCode = -966536846,S1 = 25,S2 = -1,长度= 26
2016-11-16 16:09:44.267 - 1,HashCode = -989586955 **,S1 = 9,S2 = -1,长度= 10 2016-11-16 16:09:44.358 - 1,HashCode = 450805672,S1 = 57,S2 = -1,长度= 58
2016-11-16 16:09:44.383 - 1,HashCode = -1555716066,S1 = 57,S2 = -1,长度= 58
2016-11-16 16:09:45.403 - 3XXXX,HashCode = 450805672,S1 = 0,S2 = 84,长度= 85
2016-11-16 16:09:45.418 - 3XXXX,HashCode = -1555716066,S1 = 0,S2 = 84,长度= 85
2016-11-16 16:09:45.476 - 3XXXX,HashCode = -1614800617,S1 = 0,S2 = 84,长度= 85
2016-11-16 16:09:45.481 - 3XXXX,HashCode = -966536846,S1 = 0,S2 = 84,长度= 85
2016-11-16 16:09:45.496 - 3XXXX,HashCode = -989586955,S1 = 0,S2 = 84,长度= 85
形成日志,我们可以知道:
第一个事件,变量msg等于“0 ... AAAA~”
下一个事件,然后变量msg等于“~1234567890 ...... AAAA~”
一个消息障碍,但为什么

public class MyMessageDecoder extends MessageToMessageDecoder<ByteBuf> {
private final static Logger LOGGER = LogManager.getLogger(BDCompatibleMessageDecoder.class);
 public void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
    int readableBytes = msg.readableBytes();
    int startPosition = msg.indexOf(0, readableBytes, (byte)126);
    int endPosition = msg.indexOf(startPosition + 1, readableBytes, (byte)126);
    MyMessage message = null;
    if (endPosition > startPosition + 1) {
        Boolean xxx=ctx.channel().attr(NettyConstant.NETTY_CTX_XXX).get();
        if(xxx!=null&&xxx.equals(Boolean.TRUE)&&startPosition==0){
            ctx.channel().attr(NettyConstant.NETTY_CTX_XXX).set(Boolean.FALSE);
            LOGGER.info("3XXXX,HashCode="+ctx.channel().hashCode()+",startPosition =" + startPosition + ",endPosition=" + endPosition + ",Length=" + readableBytes);
        }

        if (startPosition > 0) {
            LOGGER.info("2XXXX,HashCode="+ctx.channel().hashCode()+",startPosition =" + startPosition + ",endPosition=" + endPosition + ",Length=" + readableBytes);
        }
        byte[] escapedData = new byte[endPosition - startPosition + 1];

        msg.readBytes(escapedData);
         // todoSomeThing 
    }
    if (startPosition > 0) {
        ctx.channel().attr(NettyConstant.NETTY_CTX_XXX).set(Boolean.TRUE);
        LOGGER.info("1,HashCode="+ctx.channel().hashCode()+",startPosition =" + startPosition + ",endPosition=" + endPosition + ",Length=" + readableBytes);
    }
    if (message != null) {
        out.add(message);
    }
}

1 个答案:

答案 0 :(得分:2)

MessageToMessageDecoder假定您正在处理已解码的消息作为输入。您应该实施ByteToMessageDecoder

如果没有足够的字节来创建消息,请注意不要修改阅读器索引。还要考虑创建一个DelimiterBasedFrameDecoder并在管道中添加更早的内容。