我目前正在评估Netty处理Java客户端与C ++服务器集成的套接字通信。消息传递协议具有以下结构 -
遵循Netty api I子类LengthFieldBasedFrameDecoder接收有效的完整数据包,然后根据收到的类型解码每个数据包。从我正在使用的文档 -
它工作正常大约5分钟(我每5秒左右收到一条消息)然后解码事件包含一个比消息大小短得多的ChannelBuffer。 (我在崩溃前多次收到此消息)。然后我显然在我的内部解码代码中得到一个BufferUnderflowException。难道我做错了什么?使用LengthFieldBasedFrameDecoder时,是否应该保证消息的大小正确?
LengthFieldBasedFrameDecoder类 -
public class CisPacketDecoder extends LengthFieldBasedFrameDecoder
{
public CisPacketDecoder(int maxFrameLength, int lengthFieldOffset,
int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip) {
super(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment,
initialBytesToStrip);
}
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf)
throws Exception
{
CisMessage message = null;
int type = buf.getInt(0); //Type is always first int
CisMessageType messageType = CisMessageType.fromIntToType(type);
if(messageType != null)
{
message = messageType.getObject();
if(message != null)
{
message.decode(buf.toByteBuffer());
}
else
{
System.out.println("Unable to create message for type " + type);
}
}
//mark the Channel buf as read by moving reader index
buf.readerIndex(buf.capacity());
return message;
}
}
并在此处实例化。
public class PmcPipelineFactory implements ChannelPipelineFactory
{
@Override
public ChannelPipeline getPipeline() throws Exception
{
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("encoder", new CisPacketEncoder());
pipeline.addLast("decoder", new CisPacketDecoder(1024, 8, 4, -12, 0));
pipeline.addLast("handler", new MsgClientHandler());
return pipeline;
}
}
答案 0 :(得分:3)
你需要调用super.decode(..)并在你的decode(..)方法中对返回的ChannelBuffer进行操作。
所以就像这样;
public class CisPacketDecoder extends LengthFieldBasedFrameDecoder {
public CisPacketDecoder(int maxFrameLength, int lengthFieldOffset,
int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip) {
super(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment,
initialBytesToStrip);
}
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf)
throws Exception {
// THIS IS IMPORTANT!!!!!
ChannelBuffer decoded = (ChannelBuffer) super.decode(ctx, channel, buf);
if (decoded == null) {
return null;
}
// NOW ONLY OPERATE ON decoded
CisMessage message = null;
int type = decoded.getInt(0); //Type is always first int
CisMessageType messageType = CisMessageType.fromIntToType(type);
if(messageType != null) {
message = messageType.getObject();
if(message != null) {
message.decode(decoded.toByteBuffer());
} else {
System.out.println("Unable to create message for type " + type);
}
}
return message;
}
}
请务必查看大写评论。