首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Netty4 readableBytes太小

Netty4 readableBytes太小
EN

Stack Overflow用户
提问于 2017-06-19 21:52:58
回答 1查看 94关注 0票数 0

当使用Netty4解码时,我得到了异常。消息的长度只有640,但readableBytes不够。

代码语言:javascript
复制
 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

首先,在ChannelInitializer中添加解码器1、

代码语言:javascript
复制
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());

2、秒,解码来自服务器的字节

代码语言:javascript
复制
@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));
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-06-20 14:51:29

这个问题的原因很简单:您不能期望TCP流总是同时返回足够的数据。

解决方案也很简单:您的ChannelHandler可以只扩展ReplyingDecoder,它可以帮助您正确处理底层的steam。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44632477

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档