2016-11-16 72 views
0

我用網狀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,Length = 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〜」
one message disorder,但爲什麼
爲什麼我使用netty的時候一個消息混亂?

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

回答

2

MessageToMessageDecoder假定您正在處理一個已經解碼的消息作爲輸入。你應該實施ByteToMessageDecoder

如果您沒有足夠的字節來創建消息,請注意不要修改閱讀器索引。另外考慮創建一個DelimiterBasedFrameDecoder並在流水線中加入。

相關問題