您的位置:首页 > 运维架构 > Apache

分享一个自己在用的apache mina的解码器decoder源码

2016-02-19 15:14 746 查看
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

/**
* 序号 A B C D E
* 参数名 帧头 包长 数据包内容 CRC 校验 帧尾
* 类型 BYTE BYTE BYTE BYTE BYTE
* 字节数 2 2 N 2 2
* 标志符 0xAA 0xAA 1 7 2 0xEE 0xEE
*
*/
public class MsgServerDecoder extends CumulativeProtocolDecoder {

@Override
protected boolean doDecode(IoSession session, IoBuffer in,
ProtocolDecoderOutput out) throws Exception {

if(in.remaining() >= 4){
//缓冲区长度足够截取到协议中的包长度字节
//标记位置
in.mark();
//截取包头
byte[] msgHeader = new byte[2];
in.get(msgHeader);
//截取消息长度
byte[] msgLen = new byte[2];
in.get(msgLen);
int len = Integer.parseInt(((int)msgLen[1]&0xff)+""+((int)msgLen[0]&0xff));
if(in.remaining()<len+4){
//报文完整性不够
in.reset();
return false;
}else{
//解析报文
//TODO 此处即可根据协议将完整的报文解析成消息对象
out.write(msg);//msg即是解析完成的消息对象
return true;
}
}

return false;
}

}
上面的示例代码就是一个比较完整的mina的decode代码,代码中用到的协议写在类的注释中,有需要的朋友可以参考;如果代码中有什么错误的地方,希望大家能够帮忙指出,谢谢!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java apache mina