public class CustomProtocolDecoder extends CumulativeProtocolDecoder{
byte currentCmd = -1;
int currentSize = -1;
boolean isFirst = false;
@Override
protected boolean doDecode(IoSession is, ByteBuffer bb, ProtocolDecoderOutput pdo) throws Exception {
if(currentCmd == -1)
{
currentCmd = bb.get();
currentSize = Packet.getSize(currentCmd);
isFirst = true;
}
while(bb.remaining() > 0)
{
if(!isFirst)
{
currentCmd = bb.get();
currentSize = Packet.getSize(currentCmd);
}
else
isFirst = false;
//System.err.println(currentCmd + " " + bb.remaining() + " " + currentSize);
if(bb.remaining() >= currentSize - 1)
{
Packet p = PacketDecoder.decodePacket(bb, currentCmd);
pdo.write(p);
}
else
{
bb.flip();
return false;
}
}
if(bb.remaining() == 0)
return true;
else
return false;
}
}
有人看到这段代码有什么问题吗?当一次接收到大量数据包时,即使只连接了一个客户端,其中一个也可能在最后被切断(例如 12 个字节而不是 15 个字节),这显然很糟糕。