对解码器CumulativeProtocolDecoder的一个发现

import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

public class DecoderTest extends CumulativeProtocolDecoder {

 @Override
 protected boolean doDecode(IoSession session, ByteBuffer buff,
   ProtocolDecoderOutput out) throws Exception {
  int remain = buff.remaining();
  System.out.println("开始解码" + remain);

  if (remain >= 4) {
    int b = buff.getInt();
   System.out.println(b);
   System.out.println("是否有剩余字节:" + buff.hasRemaining());
//   out.write(t);
   return true;
  }
  return false;
 }
}


解码函数doDecode()的返回值,有两个走向:

1.对ByteBuffer有读取操作,如buff.getInt(),这时

true:继续读取剩余字节,当hasRemaining()返回false时,过滤器跳转;

false:放弃剩余字节,过滤器直接跳转。

2.没有对ByteBuffer进行任何读取操作,这时,只能返回false,MINA规定,必须保证接受量=读取量

false:继续解码

true:抛异常

猜你喜欢

转载自hibernate159.iteye.com/blog/1064041