// 解析消息 void parseMessage(byte[] bytes) { //消息读取完成后开始解析 MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length); VitByteArray arr = new VitByteArray(ms); while (arr.Postion < bytes.Length) { int messageLength = arr.ReadInt(); messageLength = Utils.BigtoLittle32(messageLength); if ((arr.Postion + messageLength - 4 + MsgHeadSize) > bytes.Length) { Debug.LogError("解析消息长度不一致[ " + messageLength + " ][ " + bytes.Length + " ]"); break; } int messageID = arr.ReadInt(); messageID = Utils.BigtoLittle32(messageID); //转换为Socket消息模型 VitSocketModel model = new VitSocketModel(); model.bodyLength = messageLength; model.messageID = messageID; byte[] pdata = new byte[messageLength]; arr.ReadBytes(pdata, 0, (uint)messageLength); model.message = pdata; // 解析proto对象 VitProtobufDispatcher.Instance.OnMessage(model); } }
// 接受消息 public void readMessage(byte[] bytes) { //消息读取完成后开始解析 MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length); VitByteArray arr = new VitByteArray(ms); while (arr.Postion < bytes.Length) { int messageLength = Utils.BigtoLittle32 (arr.ReadInt()); if ((arr.Postion + messageLength - 4 + MsgHeadSize) > bytes.Length) { int lastCount = arr.Length - arr.Postion + 4; allCount -= lastCount; Middle = new Byte[lastCount]; Buffer.BlockCopy(bytes, arr.Postion - 4, Middle, 0, lastCount); break; } int messageID = Utils.BigtoLittle32( arr.ReadInt()); //转换为Socket消息模型 VitSocketModel model = new VitSocketModel(); model.bodyLength = messageLength-4; model.messageID = messageID; byte[] data = new byte[messageLength-4]; arr.ReadBytes(data, 0, (uint)messageLength); model.message = data; messages.Add(model); } }
// 处理协议 public int OnMessage(VitSocketModel module) { int protocol = module.messageID; if (!ProtocolIdMap.ContainsKey(protocol)) { Debug.Log("OnMessage instance Error [" + protocol + "]"); return 0; } if (!CallbackMap.ContainsKey(protocol)) { Debug.Log("OnMessage callback Error [" + protocol + "]"); return 0; } // 通过反射 创建probuf对象 Type insType = ProtocolIdMap[protocol]; object insObj = Activator.CreateInstance(insType); // 解析协议内容 ProtoModelSerializer serializer = new ProtoModelSerializer(); System.IO.MemoryStream memStream = new System.IO.MemoryStream(module.message); insObj = serializer.Deserialize(memStream, insObj, insType); // 调用协议处理回调函数 return CallbackMap[protocol].OnMessage(insObj); }
// private int parseHeartBeat(MsgHeartBeatRep rep) // { // m_bHeartSend = false; // m_heartRev = 0.0f; // // return 1; // } // 解析数据包 public void parseMessage() { if (messages == null || messages.Count <= 0) { return; } //队列有消息的时候 循环读取消息进行处理 读取完当前消息后 清空消息队列 等待下帧的使用 int count = messages.Count; for (int i = 0; i < count; i++) { VitSocketModel model = messages[i]; VitProtobufDispatcher.Instance.OnMessage(model); } messages.RemoveRange (0, count); }