1
我目前正在將Netty集成到將使用XML消息進行通信的服務器上。這些XML消息實際上是已被序列化爲XML消息的對象,然後通過TCP連接發送。我可以同時發送和接收的對象,但我得到的第二個消息,執行下列例外,我發送到服務器:Netty引發IndexOutOfBoundsException
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,我認爲在處理消息後應該清除緩衝區,但事實並非如此。任何人有什麼想法可能是我的問題?
如果您認爲這是一個Netty錯誤,您可以在https://github.com/netty/netty上提出問題嗎?謝謝! – 2014-11-06 01:15:00