void encode(Message inObj, IoBuffer outBuffer) { //包头 outBuffer.Write(Message.PACKAGE_INDETIFIER); //包标识 int writePosOfLen = outBuffer.WritePos; //保存包长度写入位置 outBuffer.Write((int)0); //包长度,先点位 int writePosOfChkSum = outBuffer.WritePos; //保存包检验码写入位置 outBuffer.Write((int)0); //包检验码,先占位 //包体 int writePosOfBody = outBuffer.WritePos; //保存消息体写入位置 inObj.WriteBytes(outBuffer); //写消息体 int writePosNow = outBuffer.WritePos; //获取现在的写入位置 //回写长度 int msgBodyLen = writePosNow - writePosOfBody; //消息体写入的长度 outBuffer.WriteBack(msgBodyLen + 8, writePosOfLen); //重新写包长度,消息体N字节 + 长度字段4字节 + 检验码字段4字节 //加密 Encrypt.Tea16.EncryptInplace(outBuffer.Buffer, writePosOfBody, msgBodyLen); //检验和 int hashCode = (int)Message.BPHash(outBuffer.Buffer, writePosOfBody, msgBodyLen); outBuffer.WriteBack(hashCode, writePosOfChkSum); //写包检验和 }
public override bool setValue(IoBuffer ioBuffer, object value) { byte flag = Types.OBJECT; TypeDef def = ProtocolCoder.instance.getTypeDef(value.GetType()); if (def == null) { if (ProtocolCoder.CanRegister(value.GetType())) { ProtocolCoder.instance.Register(value.GetType()); } def = ProtocolCoder.instance.getTypeDef(value.GetType()); if (def == null) { Debuger.LogError("找不到对象的预定义:{0}", value.GetType().Name); return(false); } } // 类型标记,#### 0000 ioBuffer.Write(flag); //名字哈希值 ioBuffer.Write(def.code); // 字段数量 putVarInt32(ioBuffer, (int)def.fields.Length); //获取当前要写入的位置 var writePos1 = ioBuffer.WritePos; //对象长度字段先占位 ioBuffer.Write(0); BeginParentLog(value.GetType().Name, def.fields.Length); //Debuger.Log("{0} code:{1} 字段数:{2}", value, def.code, def.fields.Length); // 遍历属性 for (int i = 0; i < def.fields.Length; i++) { AddLogNewLine(def.fields[i].Name + ": ");//加个分隔符 if (!ProtocolCoder.instance.Encode(ioBuffer, def.fields[i].GetValue(value))) { return(false); } AddLog(",");//加个分隔符 } EndParentLog(); //再次获取当前要写入的位置 var writePos2 = ioBuffer.WritePos; //两个位置相减得到对象的序列化大小 var objectLen = writePos2 - writePos1; //更新序列化大小字段 ioBuffer.WriteBack(objectLen, writePos1); return(true); }