2017-06-19 4 views
0

Netty4でデコードすると例外が発生します。メッセージの長さは640ですが、readableBytesでは不十分です。 はNetty4 readableBytesが小さすぎます

1、まず、ChannelInitializer

private static final int MAX_FRAME_LENGTH = 1024 * 1024; 
private static final int LENGTH_FIELD_LENGTH = 4; 
private static final int LENGTH_FIELD_OFFSET = 1; 
private static final int LENGTH_ADJUSTMENT = 2; 
private static final int INITIAL_BYTES_TO_STRIP = 0; 
channelPipeline.addLast("decoder", new RemoteMassageDecoder(MAX_FRAME_LENGTH, 
       LENGTH_FIELD_LENGTH, LENGTH_FIELD_OFFSET, LENGTH_ADJUSTMENT, INITIAL_BYTES_TO_STRIP)); 
channelPipeline.addLast("encoder", new RemoteMessageEncoder()); 
にデコーダを追加

06-19 21:45:13.150 4192-4233/com.seewo.remote V/RemoteMassageDecoder: Decoder messageType == 1, messageLength: 640 
06-19 21:45:13.152 4192-4233/com.seewo.remote E/exceptionCaught: io.netty.handler.codec.DecoderException: java.lang.Exception: readableBytes is too small 

2、第二、サーバーからバイトをデコーダ

@Override 
protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception { 
    byte startCharacter = in.readByte(); 
    int messageLength = in.readInt(); 
    byte messageType = in.readByte(); 
    in.readByte(); 
    Log.v("RemoteMassageDecoder", "startCharacter == " + (startCharacter & 0xff)); 
    Log.v("RemoteMassageDecoder", "Decoder messageType == " + messageType + ", messageLength: " + messageLength); 
    if (messageLength < 0) { 
     throw new Exception("messageLength < 0"); 
    } 
    if (messageLength == 0 || messageType == 0) { 
     in.readByte(); 
     return null; 
    } 
    if (in.readableBytes() < messageLength) { 
     throw new Exception("readableBytes is too small"); 
    } 
    byte[] content = new byte[messageLength]; 
    in.readBytes(content); 
    byte stopCharacter = in.readByte(); 
    if (startCharacter != START_CHARACTER || stopCharacter != STOP_CHARACTER) { 
     return null; 
    } 
    return ProtocolPack.parseFrom(AESHelper.decryptContent(content)); 
} 
+0

[Nettyチャネルが完全なメッセージを受け取らない]の可能な複製(https://stackoverflow.com/questions/31327443/netty-channelread-not-getting-full-message) – Ferrybig

答えて

1

この問題の理由は単純です:あなたがすることはできませんTCPストリームは常に同時に十分なデータを返すと期待しています。

解決策も簡単です:あなたのChannelHandlerは、基礎となる蒸気を適切に処理するのに役立つReplyingDecoderを拡張することができます。

関連する問題