I am currently working on integrating Netty to a server that will communicate using XML messages. These XML messages are actually objects that has been serialized to XML-messages which are then sent over a TCP connection. I can both send and receive objects, but I get the following exception at the second message I send to the server:
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)
I have the following code to initialize the channel:
@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);
}
And the following code to handle messages I receive:
@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);
}
}
And this code for sending messages:
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);
}
}
I am using the java.beans.XMLDecoder and XMLEncoder for the encoding/decoding of the XML objects. As the messages I am sending is 307 in size, I thought that the buffer should be cleared after I have handled a message, however this was not the case. Anyone got any ideas on what may be my problem?
事实证明,问题是XMLEncoder在XML文档的末尾添加了一个\\ n,这在Netty开始读取XML消息时搞砸了。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.