/// <summary>
 /// 获取该packetId对应包
 /// </summary>
 /// <param name="packetId"></param>
 /// <returns></returns>
 public static Type GetTypeByPacketId(EnumPacketId packetId)
 {
     if (!Contains(packetId))
     {
         return(null);
     }
     return(Dict[packetId]);
 }
        /// <summary>
        /// 处理包的主逻辑
        /// </summary>
        /// <param name="packet"></param>
        private void ProcessPacket(IPacket packet)
        {
            EnumPacketId cmd = (EnumPacketId)packet.PacketId;

            if (!ProcessPacketDict.ContainsKey(cmd))
            {
                Debug.LogWarningFormat("Can't find method to process {0}", cmd);
                return;
            }
            ProcessPacketDict[cmd](packet);
        }
Beispiel #3
0
        /// <summary>
        /// 处理包数据
        /// </summary>
        /// <param name="data"></param>
        protected virtual void ProcessData(byte[] data)
        {
            var lengthBytes   = new byte[sizeof(int)];
            var packetIdBytes = new byte[sizeof(int)];
            int offset        = lengthBytes.Length + packetIdBytes.Length;

            if (data.Length < offset)
            {
                Debug.LogError("Process packet data length is too little.");
                return;
            }
            var bytes = new byte[data.Length - offset];

            for (int i = 0; i < lengthBytes.Length; ++i)
            {
                lengthBytes[i] = data[i];
            }

            for (int i = 0; i < packetIdBytes.Length; ++i)
            {
                packetIdBytes[i] = data[i + lengthBytes.Length];
            }
            try
            {
                EnumPacketId packetId = (EnumPacketId)BitConverter.ToInt32(packetIdBytes, 0);
                for (int i = 0; i < bytes.Length; ++i)
                {
                    bytes[i] = data[i + offset];
                }

                var packet = NetTool.GetPacketFromBytes(PacketBindings.GetTypeByPacketId(packetId), bytes);
                GetProcessPacket()(packet);
            }
            catch (Exception ex)
            {
                Debug.LogErrorFormat("Can't get packet data or process packet: {0}", ex);
            }
        }
 /// <summary>
 /// 注册cmd和处理方法
 /// </summary>
 /// <param name="cmd"></param>
 /// <param name="del"></param>
 public void RegisterProcess(EnumPacketId cmd, Action <IPacket> del)
 {
     ProcessPacketDict[cmd] = del;
 }
 /// <summary>
 /// 是否包含该packetId数据
 /// </summary>
 /// <param name="packetId"></param>
 /// <returns></returns>
 public static bool Contains(EnumPacketId packetId)
 {
     return(Dict.ContainsKey(packetId));
 }
 /// <summary>
 /// 添加包Id和类型映射
 /// </summary>
 /// <param name="packetId"></param>
 /// <param name="t"></param>
 public static void AddBinding(EnumPacketId packetId, Type t)
 {
     Dict[packetId] = t;
 }