【问题标题】:Netty throws IndexOutOfBoundsExceptionNetty 抛出 IndexOutOfBoundsException
【发布时间】:2023-03-28 13:06:01
【问题描述】:

我目前正致力于将 Netty 集成到将使用 XML 消息进行通信的服务器。这些 XML 消息实际上是已序列化为 XML 消息的对象,这些 XML 消息随后通过 TCP 连接发送。我可以发送和接收对象,但是在发送到服务器的第二条消息中出现以下异常:

java.lang.IndexOutOfBoundsException: readerIndex(306) + length(613) exceeds writerIndex(614): UnpooledUnsafeDirectByteBuf(ridx: 306, widx: 614, cap: 1024)
    at io.netty.buffer.AbstractByteBuf.checkReadableBytes(AbstractByteBuf.java:1161)
    at io.netty.buffer.AbstractByteBuf.skipBytes(AbstractByteBuf.java:734)
    at io.netty.buffer.WrappedByteBuf.skipBytes(WrappedByteBuf.java:540)
    at io.netty.handler.codec.xml.XmlFrameDecoder.decode(XmlFrameDecoder.java:176)
    at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:227)

我有以下代码来初始化频道:

@Override
public void initChannel(SocketChannel ch) throws Exception {
    LOGGER.info("Accepted connection from " + ch.remoteAddress().toString());
    ClientConnection connection = new ClientConnection(ch);
    ch.pipeline().addLast(new XmlFrameDecoder(6000), connection);
}

以下代码用于处理我收到的消息:

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    LOGGER.info("Got data");
    ByteBuf buf = (ByteBuf)msg;
    try (ByteBufInputStream is = new ByteBufInputStream(buf)) {
        Message message = MessageFactory.getInstance().deserialize(is);
        // does stuff with message...
    } catch (Throwable ex) {
        LOGGER.log(Level.WARNING, ex.getMessage(), ex);
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

还有这个发送消息的代码:

public void sendMessage(Message msg) {
    ByteBufAllocator alloc = PooledByteBufAllocator.DEFAULT;
    ByteBuf buf = alloc.buffer(1024);

    try (ByteBufOutputStream outputStream = new ByteBufOutputStream(buf)) {
        String message = MessageFactory.getInstance().serialize(msg) + "\0";
        outputStream.write(message.getBytes());
        this.socketChannel.writeAndFlush(buf);
    } catch (IOException ex) {
        LOGGER.log(Level.INFO, ex.getMessage(), ex);
    }
}

我正在使用 java.beans.XMLDecoder 和 XMLEncoder 对 XML 对象进行编码/解码。由于我发送的消息大小为 307,我认为在处理完消息后应该清除缓冲区,但事实并非如此。有人对我的问题有什么想法吗?

【问题讨论】:

    标签: java xml networking stream netty


    【解决方案1】:

    原来问题是 XMLEncoder 在 XML 文档的末尾添加了一个 \n,当 Netty 开始读取 XML 消息时它搞砸了。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-11
    • 2021-12-20
    • 2018-07-31
    • 2016-06-05
    相关资源
    最近更新 更多