---在下面编辑
我实际上是在实现Mina ProtocolCodecFilter以便从串行设备接收消息。
编解码器指定了多个不同的消息(带有它们的 pojos),即使你的实现在 99% 的时间里都能正常工作,我遇到了一种消息的问题:唯一没有固定长度的消息。我可以知道最小长度,但永远不会知道最大长度。
这是我收到的异常消息(只是重要部分):
org.apache.mina.filter.codec.ProtocolDecoderException: org.apache.mina.core.buffer.BufferDataException: dataLength: -2143812863 (Hexdump: 02 01 A2 02 01 A0 02)
at org.apache.mina.filter.codec.ProtocolCodecFilter.messageReceived(ProtocolCodecFilter.java:25
...
Caused by: org.apache.mina.core.buffer.BufferDataException: dataLength: -2143812863
at org.apache.mina.core.buffer.AbstractIoBuffer.prefixedDataAvailable(AbstractIoBuffer.java:2058)
at my.codec.in.folder.codec.MAFrameDecoder.doDecode(MAFrameDecoder.java:29)
at org.apache.mina.filter.codec.CumulativeProtocolDecoder.decode(CumulativeProtocolDecoder.java:178)
at org.apache.mina.filter.codec.ProtocolCodecFilter.messageReceived(ProtocolCodecFilter.java:241)
有时dataLength
是消极的,有时是积极的(没有找到任何关于这个原因的线索)。
MAFrameDecoder :29是我实现CumulativeProtocolDecoder
'sdoDecode()
方法的第二句话(MAX_SIZE=4096):
public boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out)
throws Exception
{
boolean result=false;
if(in.prefixedDataAvailable(4, MAX_SIZE)) //-->This is line 29
{
int length = in.getInt();
byte[] idAndData = new byte[length];
in.get(idAndData);
//do things, read from buffer, create message, out.write, etc
//if all has been correct, result=true
}
return result;
}
在通过 TCP 嗅探器调试错误时,我们发现当多个消息插入同一个 IoBuffer (in) 时会引发异常。
似乎我Decoder
根本无法处理同一缓冲区内的多条消息。但正如我之前所说,还有非固定长度的消息问题(我真的不知道它是否有一些相关性)。在其他 doDecode 实现中,我看到了另一种管理缓冲区的方法,例如:
while (in.hasRemaining())
或者
InputStream is=in.asInputStream();
无论如何,我试图避免盲目的步骤,所以这就是我在这里问这个的原因。而不是仅仅修复错误,我想知道它的原因。
希望你能帮助我,任何建议将不胜感激。:)
ps:通过缓冲区向我发送消息的编码器的autoExpand参数为false。
编辑 2014 年 10 月 11 日
我一直在探索 AbstractIoBuffer 方法并发现了这一点:
@Override
public boolean prefixedDataAvailable(int prefixLength, int maxDataLength) {
if (remaining() < prefixLength) {
return false;
}
int dataLength;
switch (prefixLength) {
case 1:
dataLength = getUnsigned(position());
break;
case 2:
dataLength = getUnsignedShort(position());
break;
case 4:
dataLength = getInt(position());
break;
default:
throw new IllegalArgumentException("prefixLength: " + prefixLength);
}
if (dataLength < 0 || dataLength > maxDataLength) {
throw new BufferDataException("dataLength: " + dataLength);
}
return remaining() - prefixLength >= dataLength;
}
我发送的 prefixLength 是 4,所以开关输入最后一个有效的情况:
dataLength = getInt(position());
之后,它会抛出带有负 dataLength 的 BufferDataException,这意味着 AbstractIoBuffer 的position()
方法正在返回一个负值。
我一直认为 nioBuffer 永远不能在其位置参数上保持负值。为什么会发生这种情况的任何线索?