簡體   English   中英

Netty拋出IndexOutOfBoundsException

[英]Netty throws IndexOutOfBoundsException

我目前正在將Netty集成到將使用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,我認為在處理完郵件后應清除緩沖區,但是事實並非如此。 有人對我的問題有任何想法嗎?

事實證明,問題是XMLEncoder在XML文檔的末尾添加了一個\\ n,這在Netty開始讀取XML消息時搞砸了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM