我目前正在将Netty集成到一个将使用XML消息进行通信的服务器上。这些XML消息实际上是已序列化为XML消息的对象,然后通过TCP连接发送这些XML消息。我可以发送和接收对象,但在我发送到服务器的第二条消息中,我得到了以下异常:
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) + " ";
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消息时,这个错误就出现了。