Beispiel #1
0
        /// <summary>
        /// 主动断线
        /// </summary>
        public void DisConnect(bool NeedReconnect = true)
        {
            if (!m_IsConnected)
            {
                return;
            }

            CLOG.I("DisConnect!");
            m_IsConnected = false;

            if (m_SocketInstance != null)
            {
                m_SocketInstance.CloseConnect();
            }

            if (m_Sender != null)
            {
                m_Sender.ClearMessage();
            }

            if (m_Receiver != null)
            {
                m_Receiver.ClearMessage();
            }

            // 如果需要主动重连,那么压入连接丢失信号
            // 由应用层检测到断线进行处理
            // 否则直接断线即可
            if (NeedReconnect)
            {
                m_Connecter.PushConnectSignal(EConnectSignal.CONNECT_LOST);
            }
        }
Beispiel #2
0
        /// <summary>
        /// 预加载所有需要用到的预制体
        /// </summary>
        /// <returns>加载成功与否</returns>
        public bool CacheAllPrefab()
        {
            try
            {
                //读取所有预制体
                UnityEngine.Object[] AllPrefabs = Resources.LoadAll(PREFAB_PATH);

                for (int i = 0; i < AllPrefabs.Length; i++)
                {
#if UNITY_EDITOR
                    if (m_PrefabCache.ContainsKey(AllPrefabs[i].name))
                    {
                        CLOG.E("the key {0} has already add to prefab cache", AllPrefabs[i].name);
                        return(false);
                    }
#endif
                    m_PrefabCache.Add(AllPrefabs[i].name, AllPrefabs[i] as GameObject);
                }

                return(true);
            }
            catch (Exception ex)
            {
                CLOG.E(ex.ToString());
                return(false);
            }
        }
Beispiel #3
0
        /// <summary>
        /// 网络初始化
        /// 创建Socket
        /// 启动各个线程
        /// </summary>
        public void Init()
        {
            CLOG.I("-- Network init --");

            // 注册所有网络消息包反射信息
            CPackageManager.Instance.PerpareNetworkPackageReflectionInformation();

            // 创建Socket
            m_SocketInstance = new CSocket();

            // 创建连接线程
            m_Connecter = new CThreadConnecter(this);

            // 创建收线程
            m_Receiver = new CThreadReceiver(this);

            // 创建发送线程
            m_Sender = new CThreadSender(this);

            m_Connecter.Start();
            m_Sender.Start();
            m_Receiver.Start();

            m_HasInit = true;
        }
Beispiel #4
0
 /// <summary>
 /// 在当前Socekt上发送CMessage消息
 /// </summary>
 /// <param name="message">消息,可由任意继承了PackageBase的对象调用 ToMessage获得</param>
 /// <returns>发送的字节数</returns>
 public int SendMessage(CMessage message)
 {
     try
     {
         int    nowSend = 0;
         byte[] data    = message.GetData();
         while (nowSend < data.Length)
         {
             int sendSize = m_Socket.Send(data, nowSend, 1024, SocketFlags.None);
             nowSend += sendSize;
         }
         return(nowSend);
     }
     catch (ArgumentNullException e)
     {
         CLOG.E(e.ToString());
         return(-1);
     }
     catch (SocketException e)
     {
         CLOG.E(e.ToString());
         return(-2);
     }
     catch (ObjectDisposedException e)
     {
         CLOG.E(e.ToString());
         return(-3);
     }
 }
Beispiel #5
0
        /// <summary>
        /// 移除掉某个对象身上的事件处理
        /// 一般在他的OnDestory里执行
        /// </summary>
        /// <param name="self">this 扩展,扩展对象必须是IMsgReceiver 的实例</param>
        /// <param name="MsgType">消息类型</param>
        public static void RemoveMessageHandler(this IMsgReceiver self, ECustomMessageType MsgType)
        {
            if (MsgType == ECustomMessageType.NULL)
            {
                CLOG.E("error msg type is {0}", MsgType);
                return;
            }

            // 没有注册该消息时的处理
            if (!m_MsgHandlerList.ContainsKey(MsgType))
            {
                return;
            }

            // 得到所有注册的处理
            var Handlers = m_MsgHandlerList[MsgType];

            // 得到数量
            var HandlerCount = Handlers.Count;

            // 倒序遍历,防止删除引起的循环异常
            for (int i = HandlerCount - 1; i >= 0; i--)
            {
                var Handler = Handlers[i];

                // 存在处理对象才调用
                if (Handler.m_Receiver == self)
                {
                    Handlers.Remove(Handler);
                }
            }
        }
Beispiel #6
0
        /// <summary>
        /// 注册消息处理
        /// </summary>
        /// <param name="self">this扩展,this必须是 ImsgReceiver 的实例</param>
        /// <param name="MsgType"> 消息名 </param>
        /// <param name="Callback"> 回调函数,无返回值,支持任意类型,任意长度的参数 </param>
        public static void AddMessageHandler(this IMsgReceiver self, ECustomMessageType MsgType, DelegateCustomMessage Callback)
        {
            if (MsgType == ECustomMessageType.NULL)
            {
                CLOG.E("error msg type is {0}", MsgType);
                return;
            }

            if (Callback == null)
            {
                CLOG.E("none call back!!", MsgType);
                return;
            }

            if (!m_MsgHandlerList.ContainsKey(MsgType))
            {
                // 如果不包含这个Key,那么就创建他
                m_MsgHandlerList[MsgType] = new List <LogicMsgHandler>();
            }

            // 防止反复注册
            foreach (var item in m_MsgHandlerList[MsgType])
            {
                if (item.m_Receiver == self && item.m_Callback == Callback)
                {
                    return;
                }
            }

            // 注册
            m_MsgHandlerList[MsgType].Add(new LogicMsgHandler(self, Callback));
        }
Beispiel #7
0
        /// <summary>
        /// 播放处理
        /// </summary>
        /// <returns>协程</returns>
        private IEnumerator PlayHandler()
        {
            while (true)
            {
                //CLOG.I( "now play animation={0} index={1} ", Animations[m_NowPlayAnimIndex].AnimState.GetDescription(), m_PlayHeadIndex );

                if (m_PlayHeadIndex < 0 || m_PlayHeadIndex >= AnimationData.Frames.Length)
                {
                    CLOG.E("frame index error!!");
                    break;
                }

                if (m_SR != null)
                {
                    m_SR.sprite = AnimationData.Frames[m_PlayHeadIndex].SpFrame;
                }
                else if (m_Image != null)
                {
                    m_Image.sprite = AnimationData.Frames[m_PlayHeadIndex].SpFrame;
                }

                /************************************************************************/
                /*                              回调处理                                */
                /************************************************************************/
                if (AnimationData.FrameCallbacks.ContainsKey(m_PlayHeadIndex))
                {
                    //如果特定帧回调存在,那么调用它
                    if (AnimationData.FrameCallbacks[m_PlayHeadIndex] != null)
                    {
                        AnimationData.FrameCallbacks[m_PlayHeadIndex](m_PlayHeadIndex);
                    }
                }
                else if (AnimationData.EveryFrameCallback != null)
                {
                    //如果特定帧回调不存在,而帧回调存在,那么调用帧回调
                    AnimationData.EveryFrameCallback(m_PlayHeadIndex);
                }

                //下一帧
                m_PlayHeadIndex++;

                //安全边界处理
                if (m_PlayHeadIndex >= AnimationData.Frames.Length)
                {
                    if (m_IsLoop)
                    {
                        m_PlayHeadIndex = 0;
                    }
                    else
                    {
                        break;
                    }
                }

                yield return(new WaitForSeconds(AnimationData.Frames[m_PlayHeadIndex].SpInteval));
            }

            m_PlayCoroutine = null;
            m_IsPlaying     = false;
        }
Beispiel #8
0
        /// <summary>
        /// 处理收到的包
        /// </summary>
        private void ProcessReceviedPackage()
        {
            CMessage message = null;

            while ((message = m_Receiver.PopReadyToHandlerPackage()) != null)
            {
                // 如果是伪造的消息,则创建时会导致读写位置到包的末尾了
                // 因此需要在这里重置归0
                message.Body.ResetPosition();

                // 包ID
                int OpCode = message.OpCode;

                // 反射出类型
                Type type = CPackageManager.Instance.ReflectionClassNameByActionID(OpCode);

                //安全处理
                if (type == null)
                {
                    CLOG.E("Reflection class name by OpCode error! OpCode={0} reflection class name = null!! please check the code", OpCode);
                    return;
                }

                // 得到该类型的处理委托
                DelegatePackageHandler DP = CPackageManager.Instance.GetPackageHandler(type);

                // 创建反射类型实例
                CPackageBase package = Activator.CreateInstance(type) as CPackageBase;

                //安全处理
                if (package == null)
                {
                    CLOG.E("create package instance error! OpCode = {0} type = {1}", OpCode, type.ToString());
                    return;
                }

                // 从message的身体中获取数据实例化对象
                try
                {
                    package.FromMessage(ref message);
                }
                catch (Exception ex)
                {
                    CLOG.E("from message error! Exception!! OpCode = {0} type={1} message={2} ", OpCode, type.ToString(), message.ToString());
                    CLOG.E(ex.ToString());
                    return;
                }

                // 调用委托,传入参数
                if (DP != null)
                {
                    DP(package);
                }
                else
                {
                    CLOG.W("ths OpCode {0} was not register handler!", OpCode);
                }
            }
        }
Beispiel #9
0
 /// <summary>
 /// 条件满足就中断条件
 /// </summary>
 /// <param name="condition">条件</param>
 public static void AssertIfFalse(bool condition)
 {
     if (condition == false)
     {
         CLOG.E("Assest.IsTrue Failed");
     }
     Assert.IsTrue(condition);
 }
Beispiel #10
0
 /// <summary>
 /// 为空就中断条件
 /// </summary>
 /// <param name="obj">条件</param>
 /// /// <param name="message">消息</param>
 public static void AssertIfNull(object obj, string message)
 {
     if (obj == null)
     {
         CLOG.E("{0} is null msg:{1}", obj.ToString(), message);
     }
     Assert.IsNotNull(obj, message);
 }
Beispiel #11
0
        /// <summary>
        /// 应用退出
        /// </summary>
        private void OnApplicationQuit()
        {
            CLOG.I("Application Quit");

            if (EventAppQuit != null)
            {
                EventAppQuit();
            }
        }
Beispiel #12
0
        /// <summary>
        /// 为空就中断条件
        /// </summary>
        /// <param name="obj">条件对象</param>
        public static void AssertIfNull(object obj)
        {
            if (obj == null)
            {
                CLOG.E("{0} is null", obj.ToString());
            }

            Assert.IsNotNull(obj);
        }
Beispiel #13
0
        /// <summary>
        /// 条件满足就中断条件,抛出文字内容
        /// </summary>
        /// <param name="condition">条件</param>
        /// <param name="message">消息</param>
        public static void AssertIfFalse(bool condition, string message)
        {
            if (condition == false)
            {
                CLOG.E(message);
            }

            Assert.IsTrue(condition, message);
        }
Beispiel #14
0
 /// <summary>
 /// 尝试连接
 /// </summary>
 public void TryConnect()
 {
     //如果已经连接就算了
     if (m_IsConnected)
     {
         CLOG.W("you has already connect to server ! so can not try to connect to server!");
         return;
     }
     CLOG.I("Try to connect to the server < IP:{0} Port:{1} >", IP, Port);
     m_Connecter.TryConnect();
 }
Beispiel #15
0
        /// <summary>
        /// 直接获得某个孩子身上的指定组件
        /// </summary>
        /// <typeparam name="T">泛型,组件类型</typeparam>
        /// <param name="target">this扩展</param>
        /// <param name="ChildName">孩子名字</param>
        /// <returns></returns>
        public static T FindChildComponent <T> (this Transform target, string ChildName)
        {
            Transform child = target.Find(ChildName);

            if (child == null)
            {
                CLOG.E("in {0} can not find child {1}", target.name, ChildName);
                return(( T )(System.Object)null);
            }

            return(child.GetComponent <T>());
        }
Beispiel #16
0
 /// <summary>
 /// 立刻切换到目标场景
 /// </summary>
 /// <param name="TargetScene">目标场景</param>
 public void ChangeSceneImmediately(string SceneName)
 {
     try
     {
         CLOG.I("ready to load scene {0} immediate", SceneName);
         CompleteCallback = null;
         SceneManager.LoadScene(SceneName, LoadSceneMode.Single);
     }
     catch (Exception ex)
     {
         CLOG.E((ex.ToString()));
     }
 }
Beispiel #17
0
        /// <summary>
        /// 添加一个同步任务到队列
        /// </summary>
        /// <param name="Mission"></param>
        public void Join(CMission Mission)
        {
            CMission CM = m_MissionQueue.Last();

            if (CM is CMissionHeap)
            {
                CM.Join(Mission);
            }
            else
            {
                CLOG.E("the last mission is not mission heap,so can not join mission to it");
            }
        }
Beispiel #18
0
        /// <summary>
        /// 应用程序暂停状态变化
        /// </summary>
        /// <param name="pause"></param>
        private void OnApplicationPause(bool pause)
        {
            CLOG.I("Application Pause state {0}", pause);
            IsApplecationPause = pause;

            if (pause)
            {
                CheckSwitchOut();
            }
            else
            {
                CheckSwitchIn();
            }
        }
Beispiel #19
0
        /// <summary>
        /// 退出
        /// </summary>
        public void Exit()
        {
            CLOG.I("End Game");

#if UNITY_EDITOR
            if (Application.platform == RuntimePlatform.WindowsEditor)
            {
                EditorApplication.isPlaying = false;
                return;
            }
#endif

            Application.Quit();
        }
Beispiel #20
0
        /// <summary>
        /// 应用程序焦点变化
        /// </summary>
        /// <param name="focus"></param>
        private void OnApplicationFocus(bool focus)
        {
            CLOG.I("Application Focus state {0}", focus);
            IsApplecationFocus = focus;

            if (focus)
            {
                CheckSwitchIn();
            }
            else
            {
                CheckSwitchOut();
            }
        }
Beispiel #21
0
        /// <summary>
        /// 每帧执行
        /// </summary>
        private void Update()
        {
            for (int i = 0; i < MissionSeqs.Count; i++)
            {
                if (MissionSeqs[i].Update( ))
                {
                    CLOG.I("the mission Seq index {0} has finish", i);
                    MissionSeqs.RemoveAt(i);
                }
            }

#if UNITY_EDITOR
            Instance.m_SequenceCount = Instance.MissionSeqs.Count;
#endif
        }
Beispiel #22
0
        /// <summary>
        /// 缓存一个预制体
        /// </summary>
        /// <param name="name"></param>
        public bool CachePrefab(string name)
        {
            //读取所有预制体
            UnityEngine.Object Prefab = Resources.Load(name);

#if UNITY_EDITOR
            if (m_PrefabCache.ContainsKey(Prefab.name))
            {
                CLOG.E("the key {0} has already add to prefab cache", Prefab.name);
                return(false);
            }
#endif
            m_PrefabCache.Add(Prefab.name, Prefab as GameObject);
            return(true);
        }
Beispiel #23
0
 /// <summary>
 /// this扩展,给所有的枚举增加一个ToString方法用来返回特性描述中的值
 /// </summary>
 /// <param name="Target">枚举对象</param>
 public static string GetDescription(this Enum Target)
 {
     try
     {
         Type      EType                = Target.GetType();
         string    FieldName            = Enum.GetName(EType, Target);
         object[]  Attributes           = EType.GetField(FieldName).GetCustomAttributes(false);
         CEnumDesc EnumDisplayAttribute = Attributes.FirstOrDefault((p) => { return(p.GetType().Equals(typeof(CEnumDesc))); }) as CEnumDesc;
         return(EnumDisplayAttribute == null ? FieldName : EnumDisplayAttribute.Desc);
     }
     catch (Exception ex)
     {
         CLOG.E(ex.ToString());
         return("");
     }
 }
Beispiel #24
0
        /// <summary>
        /// 创建UI的界面显示
        /// </summary>
        public static T CreateUI()
        {
            Type Tp = typeof(T);

            // 遍历特性
            foreach (var attr in Tp.GetCustomAttributes(false))
            {
                //UI预制体特性
                if (attr.GetType() == typeof(CUIInfo))
                {
                    return(CreateUI(attr as CUIInfo));
                }
            }

            CLOG.E("the ui {0} has no CUIInfo attr", typeof(T).ToString());
            return(null);
        }
Beispiel #25
0
        /// <summary>
        /// 异步加载场景
        /// </summary>
        /// <param name="SceneName">场景名</param>
        /// <param name="AutoSwitch">是否在加载完成自动切换到目标场景,如果切换场景使用了加载界面,那么一般需要等加载界面完成动画后再来切换,而没有使用加载界面的,可以自动切换场景</param>
        /// <returns></returns>
        IEnumerator LoadScene(string SceneName, bool AutoSwitch)
        {
            CLOG.I("ready to load scene {0} asyn", SceneName);
            m_AsyncOperator = SceneManager.LoadSceneAsync(SceneName);
            m_AsyncOperator.allowSceneActivation = AutoSwitch;
            yield return(m_AsyncOperator);

            if (CompleteCallback != null && m_AsyncOperator != null)
            {
                yield return(new WaitUntil(() => { return m_AsyncOperator.isDone; }));

                CLOG.I("scene {0} was load complete!", SceneName);
                CompleteCallback();
                m_AsyncOperator  = null;
                CompleteCallback = null;
            }
        }
Beispiel #26
0
        /// <summary>
        /// 连接到指定IP和端口
        /// </summary>
        /// <param name="host">ip或者域名</param>
        /// <param name="port">端口</param>
        /// <returns></returns>
        public bool Connect(string host, int port)
        {
            m_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            string     ip     = DomainToIP(host);
            IPAddress  ipAddr = IPAddress.Parse(ip);
            IPEndPoint ipe    = new IPEndPoint(ipAddr, port);

            try
            {
                m_Socket.Connect(ipe);
                return(true);
            }
            catch (Exception ex)
            {
                CLOG.E(ex.ToString());
                return(false);
            }
        }
Beispiel #27
0
        /// <summary>
        /// 创建UI实例并返回其上的UI组件
        ///
        /// </summary>
        /// <param name="PrefabName">预制体名</param>
        /// <param name="NeedAnimation">是否需要动画</param>
        /// <returns></returns>
        private static T InstantiateUIAndReturnComponent(CUIInfo UIInfo)
        {
            //找当前场景中的画布
            GameObject _Canvas = GameObject.Find("Canvas");

            if (_Canvas == null)
            {
                CLOG.E("now scene has not canvas");
                return(null);
            }

            //创建UI预制体实例
            GameObject CreatedUI = CPrefabManager.Instance.CreatePrefabInstance(UIInfo.PrefabName);

            if (CreatedUI == null)
            {
                CLOG.E("the UI {0} create failed", UIInfo.PrefabName);
                return(null);
            }

            //创建UI界面
            CreatedUI.name = UIInfo.PrefabName;
            RectTransform RT = CreatedUI.GetComponent <RectTransform>();

            //设置父节点
            CreatedUI.transform.SetParent(_Canvas.transform, false);
            RT.localScale = Vector3.one;

            //向UI上添加自身组件
            T Ins = GetComponentSafe(CreatedUI);

            //记录UI信息
            Ins.UIInfo = UIInfo;

            if (UIInfo.IsAnimationUI)
            {
                Ins.AnimOnCreate();
            }

            //返回UI实例
            return(Ins);
        }
Beispiel #28
0
        /// <summary>
        /// 解密一个数字
        /// </summary>
        /// <param name="number"></param>
        private int Decryption()
        {
            char[] EnStr = _data.ToCharArray();

            for (int i = 0; i < EnStr.Length; i++)
            {
                EnStr[i] ^= _key_chars[i % _key_chars.Length];
            }

            try
            {
                int result = int.Parse(new string ( EnStr ));
                return(result);
            }
            catch (Exception ex)
            {
                CLOG.E(ex.ToString());
                return(-1);
            }
        }
Beispiel #29
0
        /// <summary>
        /// 开始读取
        /// </summary>
        /// <param name="URL"></param>
        /// <param name="CompleteCallBack"></param>
        /// <param name="LoadingCallBack"></param>
        /// <param name="EHT"> URL位置是本地还是网络 </param>
        /// <returns>协程</returns>
        private IEnumerator StartLoad(string URL, DelegateHttpLoadComplete CompleteCallBack = null, DelegateHttpLoading LoadingCallBack = null, EHttpLocation EHT = EHttpLocation.REMOTE)
        {
            if (EHT == EHttpLocation.LOCAL)
            {
                URL = "file:///" + Application.persistentDataPath + "/" + URL;
                CLOG.I("read local file uri={0}", URL);
            }
            else
            {
                CLOG.I("read remote file url={0}", URL);
            }

            WWW HttpObj = new WWW(URL);

            m_NowRunningLoaderCount++;

            yield return(StartCoroutine(Loading(HttpObj, CompleteCallBack, LoadingCallBack)));

            m_NowRunningLoaderCount--;
            HttpObj.Dispose();
        }
Beispiel #30
0
        /// <summary>
        /// 得到数据
        /// </summary>
        /// <returns></returns>
        public byte[] GetData()
        {
            byte[] finalData = new byte[4 + m_BodyLength];
            int    index     = 0;

            //压入OpCode
            byte[] data = BitConverter.GetBytes(m_OpCode);
            finalData[index++] = data[0];
            finalData[index++] = data[1];

            CLOG.I("Get Data OpCode is {0} {1}", m_OpCode, Convert.ToString(m_OpCode, 2).PadLeft(16, '0'));

            //压入头长度
            data = BitConverter.GetBytes(m_BodyLength);
            finalData[index++] = data[0];
            finalData[index++] = data[1];

            CLOG.I("Get Data BodyLength is {0} {1}", m_BodyLength, Convert.ToString(m_BodyLength, 2).PadLeft(16, '0'));

            //压入身体
            data = m_Body.Buffer;
            if (data.Length < m_BodyLength)
            {
                CLOG.E("the ready push body data {0} bytes, but the message object body has only {1} bytes", m_BodyLength, data.Length);
                return(null);
            }

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < m_BodyLength; i++)
            {
                finalData[index++] = data[i];
                sb.Append(Convert.ToString(data[i], 2).PadLeft(8, '0') + ",");
            }
            CLOG.I("Get Data is {0}", sb.ToString());


            return(finalData);
        }