public static Type[] GetAllNestedTypes(this Type type)
        {
            HashSet <Type> types = new HashSet <Type>();

            while (type != null)
            {
                try
                {
                    types.UnionWith(type.GetNestedTypes());
                }
                catch (Exception e)
                {
                    if (GLog.IsLogErrorEnabled)
                    {
                        GLog.LogException(e);
                    }
                }
                try
                {
                    type = type.BaseType;
                }
                catch (Exception e)
                {
                    if (GLog.IsLogErrorEnabled)
                    {
                        GLog.LogException(e);
                    }
                    type = null;
                }
            }
            return(types.ToArray());
        }
Пример #2
0
 /// <summary>
 /// 断开
 /// </summary>
 private void _close()
 {
     _isInitThreadStart = false;
     try
     {
         if (_clientSocket != null)
         {
             _clientSocket.Shutdown(SocketShutdown.Both);
             _clientSocket.Close();
         }
     }
     catch (Exception e)
     {
         if (GLog.IsLogErrorEnabled)
         {
             GLog.LogException("socket 关闭 _clientSocket :" + e.Message);
         }
     }
     _clientSocket = null;
     CloseThread(_receiveThread);
     _receiveThread = null;
     CloseThread(_connectThread);
     _connectThread           = null;
     _currDispatchSocketState = SocketState.NONE;
     if (GLog.IsLogWarningEnabled)
     {
         GLog.LogWarning("socket 关闭完成");
     }
 }
        public static TaskProgress RunBackground(Action <TaskProgress> work)
        {
            var prog = new TaskProgress();

            ThreadPool.QueueUserWorkItem(state =>
            {
                try
                {
                    work(prog);
                }
#if UNITY_EDITOR
                catch (ThreadAbortException e)
                {
                    // 此处吃掉异常,因为线程经常在UnityEditor内被杀掉
                }
#endif
                catch (Exception e)
                {
                    if (GLog.IsLogErrorEnabled)
                    {
                        GLog.LogException(e);
                    }
                    prog.Error = e.Message;
                }
                finally
                {
                    prog.Done = true;
                }
            });
            return(prog);
        }
        /// <summary>
        /// 叠加方式打开文件
        /// </summary>
        /// <param name="path"></param>
        /// 海鸣不骑猪 2018.4.24 修改
        /// <param name="isCheckAndCreateDir">是否检查文件目录结构是否存在 如果不存在则进行创建文件</param>
        /// <returns></returns>
        public static Stream OpenAppend(this string path, bool isCheckAndCreateDir = true)
        {
            try
            {
                FileStream stream = null;
                if (isCheckAndCreateDir)
                {
                    CreateFolder(Path.GetDirectoryName(path));
                    stream = File.OpenWrite(path);
                }
                else ///如果是运行时不检查并创建文件夹 则需要做安全处理防止在运行过程中文件被销毁
                {
                    try
                    {
                        stream = File.OpenWrite(path);
                    }
                    catch (Exception e)
                    {
                        if (GLog.IsLogErrorEnabled)
                        {
                            GLog.LogException(e);
                        }
                        CreateFolder(Path.GetDirectoryName(path));
                        stream = File.OpenWrite(path);
                    }
                }

                if (stream != null)
                {
                    if (stream.CanSeek)
                    {
                        stream.Seek(0, SeekOrigin.End);
                    }
                    else
                    {
                        if (GLog.IsLogErrorEnabled)
                        {
                            GLog.LogError(path + " cannot append.");
                        }
                    }
                }
                return(stream);
            }
            catch (Exception e)
            {
                if (GLog.IsLogErrorEnabled)
                {
                    GLog.LogException(e);
                }
                return(null);
            }
        }
 public static void CreateFolder(this string path)
 {
     try
     {
         Directory.CreateDirectory(path);
     }
     catch (Exception e)
     {
         if (GLog.IsLogErrorEnabled)
         {
             GLog.LogException(e);
         }
     }
 }
Пример #6
0
        /// <summary>
        /// 连接操作完成
        /// 可能成功,可能失败
        /// </summary>
        /// <param name="iar"></param>
        private void _onConnect_complete(IAsyncResult iar)
        {
            try
            {
                Socket client = (Socket)iar.AsyncState;
                client.EndConnect(iar);

                if (GLog.IsLogInfoEnabled)
                {
                    GLog.LogInfo("_onConnect_complete step 1");
                }
                var clientSocket = _clientSocket;
                if (clientSocket != null && !clientSocket.Connected)
                {
                    if (GLog.IsLogInfoEnabled)
                    {
                        GLog.LogInfo("_onConnect_complete step 2");
                    }
                    OnChanageSocketState(SocketState.CONNECT_FAIL);
                    _close();
                    return;
                }

                _isInitThreadStart          = true;
                _receiveThread              = new Thread(_onReceiveSocket);
                _receiveThread.IsBackground = true;
                _receiveThread.Start();
                if (connetcSuccess != null)
                {
                    connetcSuccess();
                }
                OnChanageSocketState(SocketState.SUCCESS);
            }
            catch (Exception e)
            {
                if (GLog.IsLogErrorEnabled)
                {
                    GLog.LogException("_onConnect_complete = " + e.Message);
                }
                if (e is ThreadAbortException)
                {
                    // ThreadAbortException异常比较特殊,只要Abort一定会抛出此异常,属于正常现象,不需要记录错误。
                    // 但是,ThreadAbortException即便被catch了,也会再次抛出,然而抛出异常可能导致游戏闪退,所以必须阻止此异常再次抛出。
                    // 因此,这里调用Thread.ResetAbort阻止线程被中止,并且break跳出循环以便线程正常结束。
                    Thread.ResetAbort();
                    return;
                }
                _close();
            }
        }
Пример #7
0
 /// <summary>
 /// 发送消息结果回掉,可判断当前网络状态
 /// </summary>
 /// <param name="asyncSend"></param>
 private void _onSendMsg(IAsyncResult asyncSend)
 {
     try
     {
         Socket client = (Socket)asyncSend.AsyncState;
         client.EndSend(asyncSend);
     }
     catch (Exception e)
     {
         if (GLog.IsLogErrorEnabled)
         {
             GLog.LogException("send msg exception:" + e.Message);
         }
     }
 }
 public static Stream OpenRead(this string path)
 {
     try
     {
         return(File.OpenRead(path));
     }
     catch (Exception e)
     {
         if (GLog.IsLogErrorEnabled)
         {
             GLog.LogException(e);
         }
         return(null);
     }
 }
 public static bool IsFileExist(this string path)
 {
     try
     {
         return(File.Exists(path));
     }
     catch (Exception e)
     {
         if (GLog.IsLogErrorEnabled)
         {
             GLog.LogException(e);
         }
         return(false);
     }
 }
 public static void DeleteFile(this string path)
 {
     try
     {
         File.Delete(path);
     }
     catch (DirectoryNotFoundException) { }
     catch (Exception e)
     {
         if (GLog.IsLogErrorEnabled)
         {
             GLog.LogException(e);
         }
     }
 }
 public void LoadLightProbes(int index)
 {
     if (Application.isEditor && !Application.isPlaying)
     {
         PrepareLightProbeArrays();
     }
     try
     {
         LightmapSettings.lightProbes.bakedProbes = lightProbesRuntime[index];
     }
     catch (Exception e)
     {
         if (GLog.IsLogErrorEnabled)
         {
             GLog.LogException("Warning, error when trying to load lightprobes for scenario " + index + "\n" + e);
         }
     }
 }
Пример #12
0
        /// <summary>
        /// 连接
        /// </summary>
        private void _onConnet()
        {
            try
            {
                _init();
                // 解析IP地址
                IPAddress[] ips       = Dns.GetHostAddresses(_currIP);
                IPAddress   ipAddress = ips[0];
                // 支持ipv4和ipv6
                _clientSocket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint ipEndpoint = new IPEndPoint(ipAddress, _currPort);
                // 异步连接
                IAsyncResult result  = _clientSocket.BeginConnect(ipEndpoint, new AsyncCallback(_onConnect_complete), _clientSocket);
                bool         success = result.AsyncWaitHandle.WaitOne(TIME_OUT, true);
                // 超时
                if (!success)
                {
                    OnChanageSocketState(SocketState.TIME_OUT);
                }
            }
            catch (Exception e)
            {
                if (GLog.IsLogErrorEnabled)
                {
                    GLog.LogException("_onConnet Exception = " + e.Message);
                }

                if (e is ThreadAbortException)
                {
                    // ThreadAbortException异常比较特殊,只要Abort一定会抛出此异常,属于正常现象,不需要记录错误。
                    // 但是,ThreadAbortException即便被catch了,也会再次抛出,然而抛出异常可能导致游戏闪退,所以必须阻止此异常再次抛出。
                    // 因此,这里调用Thread.ResetAbort阻止线程被中止,并且break跳出循环以便线程正常结束。
                    Thread.ResetAbort();
                    return;
                }

                if (e is FormatException || e is ArgumentException || e is SocketException || e is ArgumentOutOfRangeException || e is ArgumentNullException)
                {
                    OnChanageSocketState(SocketState.IP_ERR);
                    return;
                }
                OnChanageSocketState(SocketState.CONNECT_FAIL);
            }
        }
 public static StreamWriter OpenWriteText(this string path)
 {
     try
     {
         var stream = OpenWrite(path);
         if (stream != null)
         {
             return(new StreamWriter(stream));
         }
     }
     catch (Exception e)
     {
         if (GLog.IsLogErrorEnabled)
         {
             GLog.LogException(e);
         }
     }
     return(null);
 }
Пример #14
0
 /// <summary>
 /// 关闭线程
 /// </summary>
 private void CloseThread(Thread thread)
 {
     try
     {
         if (thread != null && thread.IsAlive)
         {
             thread.Abort();
             thread.Join();
             thread = null;
         }
     }
     catch (Exception e)
     {
         if (GLog.IsLogErrorEnabled)
         {
             GLog.LogException("CloseThread :" + e.Message);
         }
     }
 }
 public static StreamWriter OpenAppendText(this string path, bool isCheckAndCreateDir = true)
 {
     try
     {
         var stream = OpenAppend(path, isCheckAndCreateDir);
         if (stream != null)
         {
             return(new StreamWriter(stream));
         }
     }
     catch (Exception e)
     {
         if (GLog.IsLogErrorEnabled)
         {
             GLog.LogException(e);
         }
     }
     return(null);
 }
Пример #16
0
 private void DispatchCheckSocketState()
 {
     if (_currDispatchSocketState == _currSocketState || _luaCallback == null)
     {
         return;
     }
     try
     {
         if (GLog.IsLogWarningEnabled)
         {
             GLog.LogWarning("socket DispatchCheckSocketState 派发事件 currDispatchSocketState :[" + _currDispatchSocketState + "]  _currSocketState :" + _currSocketState);
         }
         _currDispatchSocketState = _currSocketState;
         _luaCallback((int)_currSocketState);
     }
     catch (Exception e)
     {
         GLog.LogException("DispatchCheckSocketState ==> " + e.Message);
     }
 }
Пример #17
0
 private void DispatchSendMsgBase()
 {
     if (_clientSocket == null || !_clientSocket.Connected || _sendDataCaching == null)
     {
         return;
     }
     try
     {
         SendDataCaching data;
         while (_sendDataCaching.Count > 0)
         {
             data = _sendDataCaching.Dequeue();
             SendMsgBase(data.protocallType, data.data);
         }
     }
     catch (Exception e)
     {
         GLog.LogException("DispatchSendMsgBase ==> " + e.Message);
     }
 }
        public static void CopyFile(this string src, string dst)
        {
            if (IsFileSameName(src, dst))
            {
                return;
            }

            if (!string.IsNullOrEmpty(src) && !string.IsNullOrEmpty(dst))
            {
                var srcs = OpenRead(src);
                if (srcs != null)
                {
                    try
                    {
                        using (var dsts = OpenWrite(dst))
                        {
                            CopyTo(srcs, dsts);
                        }
                    }
                    catch (Exception e)
                    {
                        if (GLog.IsLogErrorEnabled)
                        {
                            GLog.LogException(e);
                        }
                        throw;
                    }
                    finally
                    {
                        srcs.Dispose();
                    }
                }
                else
                {
                    if (GLog.IsLogInfoEnabled)
                    {
                        GLog.LogInfo(src + " cannot be read.");
                    }
                }
            }
        }
        public static bool IsFileSameName(this string src, string dst)
        {
            try
            {
                if (src == dst)
                {
                    return(true);
                }
                if (string.IsNullOrEmpty(src))
                {
                    if (string.IsNullOrEmpty(dst))
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
                else if (string.IsNullOrEmpty(dst))
                {
                    return(false);
                }

                if (Path.GetFullPath(src) == Path.GetFullPath(dst))
                {
                    return(true);
                }
            }
            catch (Exception e)
            {
                if (GLog.IsLogErrorEnabled)
                {
                    GLog.LogException(e);
                }
            }
            return(false);
        }
 public static string[] GetAllFiles(this string dir)
 {
     try
     {
         List <string> files = new List <string>();
         files.AddRange(Directory.GetFiles(dir));
         var subs = Directory.GetDirectories(dir);
         foreach (var sub in subs)
         {
             files.AddRange(GetAllFiles(sub));
         }
         return(files.ToArray());
     }
     catch (DirectoryNotFoundException) { }
     catch (Exception e)
     {
         if (GLog.IsLogErrorEnabled)
         {
             GLog.LogException(e);
         }
     }
     return(new string[0]);
 }
Пример #21
0
 /// <summary>
 /// 接受网络数据
 /// 在接收线程中
 /// </summary>
 private void _onReceiveSocket()
 {
     while (true)
     {
         try
         {
             var receiveThread = _receiveThread;
             if (!_isInitThreadStart || _clientSocket == null || receiveThread == null || !receiveThread.IsAlive)
             {
                 return;
             }
             if (_clientSocket != null && !_clientSocket.Connected)
             {
                 OnChanageSocketState(SocketState.SOCKET_ERR);
                 return;
             }
             ///Available 属性用于确定在网络缓冲区中排队等待读取的数据的量。 如果数据可用,可调用 Read 获取数据。 如果无数据可用,则 Available 属性返回 0
             if (_clientSocket.Available <= 0)
             {
                 Thread.Sleep(0);
                 continue;
             }
             int receiveLength = _clientSocket.Receive(_tmpReceiveBuff);
             if (receiveLength <= 0)
             {
                 Thread.Sleep(0);
                 continue;
             }
             // 将收到的数据添加到缓存器中
             _databuffer.AddBuffer(_tmpReceiveBuff, receiveLength);
             TmpSocketData _socketData;
             // 取出一条完整数据
             while (_databuffer.GetData(out _socketData))
             {
                 var recvQueue = _recvQueue;
                 if (recvQueue != null)
                 {
                     recvQueue.Enqueue(_socketData);
                 }
             }
             Thread.Sleep(0);
         }
         catch (Exception e)
         {
             if (GLog.IsLogErrorEnabled)
             {
                 GLog.LogException("_onReceiveSocket Exception = " + e.Message);
             }
             if (e is ThreadAbortException)
             {
                 // ThreadAbortException异常比较特殊,只要Abort一定会抛出此异常,属于正常现象,不需要记录错误。
                 // 但是,ThreadAbortException即便被catch了,也会再次抛出,然而抛出异常可能导致游戏闪退,所以必须阻止此异常再次抛出。
                 // 因此,这里调用Thread.ResetAbort阻止线程被中止,并且break跳出循环以便线程正常结束。
                 Thread.ResetAbort();
                 return;
             }
             _close();
             return;
         }
     }
 }
    IEnumerator PreStartCheck()
    {
        if (GLog.IsLogInfoEnabled)
        {
            GLog.LogInfo("PreStartCheck run 0");
        }
        string ready = LuaEvent.TrigClrEvent <string>("SDK_READY_TO_START");

        if (GLog.IsLogInfoEnabled)
        {
            GLog.LogInfo("PreStartCheck run 1");
        }
        if (!string.IsNullOrEmpty(ready))
        {
            if (GLog.IsLogInfoEnabled)
            {
                GLog.LogInfo("PreStartCheck run 2");
            }
            while (ready != "ready")
            {
                yield return(null);

                if (GLog.IsLogInfoEnabled)
                {
                    GLog.LogInfo("PreStartCheck run 3");
                }
                ready = LuaEvent.TrigClrEvent <string>("SDK_READY_TO_START");
            }
        }

#if EFUN_SDK_EN || EFUN_SDK_TW
        // obb
        ResManager.Init();
#endif

        if (GLog.IsLogInfoEnabled)
        {
            GLog.LogInfo("PreStartCheck run 4");
        }
        var workpending = ResManager.MovePendingUpdate(LoadingReport);
        if (workpending != null)
        {
            while (workpending.MoveNext())
            {
                yield return(workpending.Current);

                if (GLog.IsLogInfoEnabled)
                {
                    GLog.LogInfo("PreStartCheck run 5");
                }
            }
        }

#if UNITY_EDITOR && !USE_CLIENT_RES_MANAGER
        ResManager.RecordCacheVersion("editor", int.MaxValue);
#else
        IEnumerator work = null;
        try
        {
            SetLoadingPhaseAmount(3);
            SetLoadingPhase(0);
            work = ResManager.DecompressScriptBundle("default", LoadingReport);
        }
        catch (Exception e)
        {
            if (GLog.IsLogErrorEnabled)
            {
                GLog.LogException(e);
            }
            LoadingReportError();
            yield break;
        }
        if (work != null)
        {
            while (true)
            {
                try
                {
                    if (!work.MoveNext())
                    {
                        break;
                    }
                }
                catch (Exception e)
                {
                    if (GLog.IsLogErrorEnabled)
                    {
                        GLog.LogException(e);
                    }
                    LoadingReportError();
                    yield break;
                }
                yield return(work.Current);
            }
        }
        foreach (var flag in ResManager.GetDistributeFlags())
        {
            try
            {
                //SetLoadingPhase(loadingPhase + 1);
                work = ResManager.DecompressScriptBundle("distribute/" + flag, LoadingReport);
            }
            catch (Exception e)
            {
                if (GLog.IsLogErrorEnabled)
                {
                    GLog.LogException(e);
                }
                LoadingReportError();
                yield break;
            }
            if (work != null)
            {
                while (true)
                {
                    try
                    {
                        if (!work.MoveNext())
                        {
                            break;
                        }
                    }
                    catch (Exception e)
                    {
                        if (GLog.IsLogErrorEnabled)
                        {
                            GLog.LogException(e);
                        }
                        LoadingReportError();
                        yield break;
                    }
                    yield return(work.Current);
                }
            }
        }
        try
        {
            SetLoadingPhase(loadingPhase + 1);
            work = ResManager.UpdateResourceBundleLocalAll(LoadingReport);
        }
        catch (Exception e)
        {
            if (GLog.IsLogErrorEnabled)
            {
                GLog.LogException(e);
            }
            LoadingReportError();
            yield break;
        }
        if (work != null)
        {
            while (true)
            {
                try
                {
                    if (!work.MoveNext())
                    {
                        break;
                    }
                }
                catch (Exception e)
                {
                    if (GLog.IsLogErrorEnabled)
                    {
                        GLog.LogException(e);
                    }
                    LoadingReportError();
                    yield break;
                }
                yield return(work.Current);
            }
        }
        try
        {
            SetLoadingPhase(loadingPhase + 1);
            work = ResManager.SplitResIndexAsyncAll(LoadingReport);
        }
        catch (Exception e)
        {
            if (GLog.IsLogErrorEnabled)
            {
                GLog.LogException(e);
            }
            LoadingReportError();
            yield break;
        }
        if (work != null)
        {
            while (true)
            {
                try
                {
                    if (!work.MoveNext())
                    {
                        break;
                    }
                }
                catch (Exception e)
                {
                    if (GLog.IsLogErrorEnabled)
                    {
                        GLog.LogException(e);
                    }
                    LoadingReportError();
                    yield break;
                }
                yield return(work.Current);
            }
        }
        yield return(new WaitForEndOfFrame());

        if (ResManager.TryGetAssetDesc("Assets/CapstonesRes/Common/Fonts/CapstonesPlaceHolder.otf") != null)
        {
            ResManager.MarkPermanent("Assets/CapstonesRes/Common/Fonts/DistributeFontInfo.fi.txt");
            ResManager.MarkPermanent("Assets/CapstonesRes/Common/Fonts/CapstonesPlaceHolder.otf");
            ResManager.LoadRes("Assets/CapstonesRes/Common/Fonts/DistributeFontInfo.fi.txt");
            ResManager.LoadRes("Assets/CapstonesRes/Common/Fonts/CapstonesPlaceHolder.otf");
        }
#endif

        LoadingReport("WaitForBiReport", null);
        yield return(new WaitForEndOfFrame());

        try
        {
            //ResManager.UnloadAllRes();
            GC.Collect();
            //GC.WaitForPendingFinalizers();
        }
        catch (Exception e)
        {
            if (GLog.IsLogErrorEnabled)
            {
                GLog.LogException(e);
            }
            LoadingReportError();
            yield break;
        }

        //LuaBehaviour.luaEnv.DoString("require 'main'");
        UnityEngine.SceneManagement.SceneManager.LoadScene("DemoEntry");

        yield break;
    }
Пример #23
0
 public virtual object[] Call(object target, params object[] args)
 {
     try
     {
         object[] rargs;
         if (_LastIsParams >= 0)
         {
             rargs = ObjectPool.GetParamsFromPool(_LastIsParams + 1);
             for (int i = 0; i < _LastIsParams; ++i)
             {
                 object arg = null;
                 if (i < args.Length)
                 {
                     arg = args[i];
                 }
                 rargs[i] = arg.ConvertTypeRaw(_MethodParamTypes[i]);
             }
             Array arr = null;
             if (args.Length == _LastIsParams + 1)
             {
                 var raw = args[_LastIsParams];//.UnwrapDynamic();
                 if (_MethodParamTypes[_LastIsParams].IsInstanceOfType(raw))
                 {
                     arr = raw as Array;
                     rargs[_LastIsParams] = arr;
                 }
             }
             if (arr == null)
             {
                 int arrLen = 0;
                 if (args.Length > _LastIsParams)
                 {
                     arrLen = args.Length - _LastIsParams;
                 }
                 arr = Array.CreateInstance(_MethodParamTypes[_LastIsParams].GetElementType(), arrLen);
                 rargs[_LastIsParams] = arr;
                 for (int i = 0; i < arr.Length; ++i)
                 {
                     arr.SetValue(args[_LastIsParams + i].ConvertTypeRaw(_MethodParamTypes[_LastIsParams].GetElementType()), i);
                 }
             }
         }
         else
         {
             int len = _MethodParamTypes.Count;
             rargs = ObjectPool.GetParamsFromPool(len);
             for (int i = 0; i < len; ++i)
             {
                 object arg = null;
                 if (i < args.Length)
                 {
                     arg = args[i];
                 }
                 rargs[i] = arg.ConvertTypeRaw(_MethodParamTypes[i]);
             }
         }
         object result = null;
         if (Method is ConstructorInfo)
         {
             result = ((ConstructorInfo)Method).Invoke(rargs);
         }
         else
         {
             // ideally, we should not call the overridden method and call exactly the method provided by the MethodInfo.
             // but the MethodInfo will always call the finally overridden method provided by the target object.
             // there is a solution that creates delegate with RuntimeMethodHandle using Activator class.
             // but the delegate itself is to be declared. so this is not the common solution.
             // see http://stackoverflow.com/questions/4357729/use-reflection-to-invoke-an-overridden-base-method
             // the temporary solution is we should declare public non-virtual method in the derived class and call base.XXX in this method and we can call this method.
             result = Method.Invoke(target, rargs);
         }
         var rv = ObjectPool.GetReturnValueFromPool(1 + (_OutParamIndices == null ? 0 : _OutParamIndices.Length));
         rv[0] = result;
         var seq = 0;
         if (_OutParamIndices != null && rargs != null)
         {
             foreach (var index in _OutParamIndices)
             {
                 if (index >= 0 && index < rargs.Length)
                 {
                     rv[++seq] = rargs[index];
                 }
             }
         }
         ObjectPool.ReturnParamsToPool(rargs);
         return(rv);
     }
     catch (Exception e)
     {
         // TODO: the debug info will decrease the performance. we should develop a generic lua-call-clr log.
         // perhaps we should make a Call and a TryCall. perhaps we should show which lua-state is doing the log. perhaps we should should lua-stack
         if (GLog.IsLogErrorEnabled)
         {
             GLog.LogException("Unable To Call: " + Method.Name + "@" + Method.DeclaringType.Name + " \n" + e.ToString());
         }
     }
     return(null);
 }
Пример #24
0
        public void RequestWork(object state)
        {
            try
            {
#if NETFX_CORE
                System.Net.HttpWebRequest req = System.Net.HttpWebRequest.CreateHttp(new Uri(_Url));
#else
#if (UNITY_5 || UNITY_5_3_OR_NEWER)
                System.Net.HttpWebRequest req = System.Net.HttpWebRequest.Create(new Uri(_Url)) as System.Net.HttpWebRequest;
#else
                System.Net.HttpWebRequest req = new System.Net.HttpWebRequest(new Uri(_Url));
#endif
                req.KeepAlive = false;
#endif

                try
                {
                    lock (_CloseLock)
                    {
                        if (_Closed)
                        {
#if !HTTP_REQ_DONOT_ABORT
                            req.Abort();
#endif
                            if (_Status != RequestStatus.Finished)
                            {
                                _Error  = "Request Error (Cancelled)";
                                _Status = RequestStatus.Finished;
                            }
                            return;
                        }
                        _InnerReq = req;
                    }

#if !NETFX_CORE
                    req.Timeout          = int.MaxValue;
                    req.ReadWriteTimeout = int.MaxValue;
#if !HTTP_REQ_DONOT_ABORT
                    if (_Timeout > 0)
                    {
                        req.Timeout          = _Timeout;
                        req.ReadWriteTimeout = _Timeout;
                    }
#endif
#endif
                    if (_Headers != null)
                    {
                        foreach (var kvp in _Headers.Data)
                        {
                            var key = kvp.Key;
                            var val = (kvp.Value ?? "").ToString();
                            if (key.IndexOfAny(new[] { '\r', '\n', ':', }) >= 0)
                            {
                                continue; // it is dangerous, may be attacking.
                            }
                            if (val.IndexOfAny(new[] { '\r', '\n', }) >= 0)
                            {
                                continue; // it is dangerous, may be attacking.
                            }
                            else
                            {
                                req.Headers[key] = val;
                            }
                        }
                    }
                    if (_RangeEnabled)
                    {
                        long filepos = 0;
                        if (_Dest != null)
                        {
                            using (var stream = PlatExt.PlatDependant.OpenRead(_Dest))
                            {
                                if (stream != null)
                                {
                                    try
                                    {
                                        filepos = stream.Length;
                                    }
                                    catch (Exception e)
                                    {
                                        if (GLog.IsLogErrorEnabled)
                                        {
                                            GLog.LogException(e);
                                        }
                                    }
                                }
                            }
                        }
                        if (filepos <= 0)
                        {
                            if (_DestStream != null)
                            {
                                try
                                {
                                    if (_DestStream.CanSeek)
                                    {
                                        filepos = _DestStream.Length;
                                    }
                                }
                                catch (Exception e)
                                {
                                    if (GLog.IsLogErrorEnabled)
                                    {
                                        GLog.LogException(e);
                                    }
                                }
                            }
                        }
                        if (filepos > 0)
                        {
                            if (filepos > int.MaxValue)
                            {
                                _RangeEnabled = false;
                            }
                            else
                            {
                                req.AddRange((int)filepos);
                            }
                        }
                        else
                        {
                            _RangeEnabled = false;
                        }
                    }
                    if (_Data != null && (_Data.Count > 0 || _Data.Encoded != null))
                    {
                        req.Method = "POST";
                        var data = _Data.Encoded;
                        if (data == null)
                        {
                            req.ContentType = _Data.ContentType;
                            data            = _Data.Encode();
                        }
                        else
                        {
                            req.ContentType = "application/octet-stream";
                        }

#if NETFX_CORE
                        var tstream = req.GetRequestStreamAsync();
                        if (_Timeout > 0)
                        {
                            if (!tstream.Wait(_Timeout))
                            {
                                throw new TimeoutException();
                            }
                        }
                        else
                        {
                            tstream.Wait();
                        }
                        var stream = tstream.Result;
#else
                        req.ContentLength = data.Length;
                        var stream = req.GetRequestStream();
#endif

                        lock (_CloseLock)
                        {
                            if (_Closed)
                            {
#if !HTTP_REQ_DONOT_ABORT
                                req.Abort();
#endif
                                if (_Status != RequestStatus.Finished)
                                {
                                    _Error  = "Request Error (Cancelled)";
                                    _Status = RequestStatus.Finished;
                                }
                                return;
                            }
                        }
                        if (stream != null)
                        {
#if NETFX_CORE
                            if (_Timeout > 0)
                            {
                                stream.WriteTimeout = _Timeout;
                            }
                            else
                            {
                                stream.WriteTimeout = int.MaxValue;
                            }
#endif

                            try
                            {
                                stream.Write(data, 0, data.Length);
                                stream.Flush();
                            }
                            finally
                            {
                                stream.Dispose();
                            }
                        }
                    }
                    else
                    {
                    }
                    lock (_CloseLock)
                    {
                        if (_Closed)
                        {
#if !HTTP_REQ_DONOT_ABORT
                            req.Abort();
#endif
                            if (_Status != RequestStatus.Finished)
                            {
                                _Error  = "Request Error (Cancelled)";
                                _Status = RequestStatus.Finished;
                            }
                            return;
                        }
                    }
#if NETFX_CORE
                    var tresp = req.GetResponseAsync();
                    if (_Timeout > 0)
                    {
                        if (!tresp.Wait(_Timeout))
                        {
                            throw new TimeoutException();
                        }
                    }
                    else
                    {
                        tresp.Wait();
                    }
                    var resp = tresp.Result;
#else
                    var resp = req.GetResponse();
#endif
                    lock (_CloseLock)
                    {
                        if (_Closed)
                        {
#if !HTTP_REQ_DONOT_ABORT
                            req.Abort();
#endif
                            if (_Status != RequestStatus.Finished)
                            {
                                _Error  = "Request Error (Cancelled)";
                                _Status = RequestStatus.Finished;
                            }
                            return;
                        }
                    }
                    if (resp != null)
                    {
                        try
                        {
                            _Total = (ulong)resp.ContentLength;
                        }
                        catch
                        {
                        }
                        try
                        {
                            _RespHeaders = new HttpRequestData();
                            foreach (var key in resp.Headers.AllKeys)
                            {
                                _RespHeaders.Add(key, resp.Headers[key]);
                            }

                            if (_RangeEnabled)
                            {
                                bool rangeRespFound = false;
                                foreach (var key in resp.Headers.AllKeys)
                                {
                                    if (key.ToLower() == "content-range")
                                    {
                                        rangeRespFound = true;
                                    }
                                }
                                if (!rangeRespFound)
                                {
                                    _RangeEnabled = false;
                                }
                            }

                            var stream = resp.GetResponseStream();
                            lock (_CloseLock)
                            {
                                if (_Closed)
                                {
#if !HTTP_REQ_DONOT_ABORT
                                    req.Abort();
#endif
                                    if (_Status != RequestStatus.Finished)
                                    {
                                        _Error  = "Request Error (Cancelled)";
                                        _Status = RequestStatus.Finished;
                                    }
                                    return;
                                }
                            }
                            if (stream != null)
                            {
#if NETFX_CORE
                                if (_Timeout > 0)
                                {
                                    stream.ReadTimeout = _Timeout;
                                }
                                else
                                {
                                    stream.ReadTimeout = int.MaxValue;
                                }
#endif
                                Stream streamd = null;
                                try
                                {
                                    byte[] buffer   = new byte[1024 * 1024];
                                    ulong  totalcnt = 0;
                                    int    readcnt  = 0;

                                    bool mem = false;
                                    if (_Dest != null)
                                    {
                                        if (_RangeEnabled)
                                        {
                                            streamd  = Capstones.PlatExt.PlatDependant.OpenAppend(_Dest);
                                            totalcnt = (ulong)streamd.Length;
                                        }
                                        else
                                        {
                                            streamd = Capstones.PlatExt.PlatDependant.OpenWrite(_Dest);
                                        }
#if HTTP_REQ_DONOT_ABORT
                                        if (streamd != null)
                                        {
                                            _CloseList.Add(streamd);
                                        }
#endif
                                    }
                                    if (streamd == null)
                                    {
                                        if (_DestStream != null)
                                        {
                                            if (_RangeEnabled)
                                            {
                                                _DestStream.Seek(0, SeekOrigin.End);
                                                totalcnt = (ulong)_DestStream.Length;
                                            }
                                            streamd = _DestStream;
                                        }
                                        else
                                        {
                                            mem     = true;
                                            streamd = new MemoryStream();
#if HTTP_REQ_DONOT_ABORT
                                            _CloseList.Add(streamd);
#endif
                                        }
                                    }

                                    if (_Total > 0)
                                    {
                                        _Total += totalcnt;
                                    }

                                    do
                                    {
                                        lock (_CloseLock)
                                        {
                                            if (_Closed)
                                            {
#if !HTTP_REQ_DONOT_ABORT
                                                req.Abort();
#endif
                                                if (_Status != RequestStatus.Finished)
                                                {
                                                    _Error  = "Request Error (Cancelled)";
                                                    _Status = RequestStatus.Finished;
                                                }
                                                return;
                                            }
                                        }
                                        try
                                        {
                                            readcnt = 0;
                                            readcnt = stream.Read(buffer, 0, 1024 * 1024);
                                            if (readcnt <= 0)
                                            {
                                                stream.ReadByte(); // when it is closed, we need read to raise exception.
                                                break;
                                            }

                                            streamd.Write(buffer, 0, readcnt);
                                            streamd.Flush();
                                        }
                                        catch (TimeoutException te)
                                        {
                                            if (GLog.IsLogErrorEnabled)
                                            {
                                                GLog.LogException(te);
                                            }
                                            _Error = "timedout";
                                        }
                                        catch (System.Net.WebException we)
                                        {
                                            if (GLog.IsLogErrorEnabled)
                                            {
                                                GLog.LogException(we);
                                            }
#if NETFX_CORE
                                            if (we.Status.ToString() == "Timeout")
#else
                                            if (we.Status == System.Net.WebExceptionStatus.Timeout)
#endif
                                            {
                                                _Error = "timedout";
                                            }
                                            else
                                            {
                                                _Error = "Request Error (Exception):\n" + we.ToString();
                                            }
                                        }
                                        catch (Exception e)
                                        {
                                            if (GLog.IsLogErrorEnabled)
                                            {
                                                GLog.LogException(e);
                                            }
                                            _Error = "Request Error (Exception):\n" + e.ToString();
                                        }
                                        lock (_CloseLock)
                                        {
                                            if (_Closed)
                                            {
#if !HTTP_REQ_DONOT_ABORT
                                                req.Abort();
#endif
                                                if (_Status != RequestStatus.Finished)
                                                {
                                                    _Error  = "Request Error (Cancelled)";
                                                    _Status = RequestStatus.Finished;
                                                }
                                                return;
                                            }
                                        }
                                        totalcnt += (ulong)readcnt;
                                        _Length   = totalcnt;
                                        //Capstones.PlatExt.PlatDependant.LogInfo(readcnt);
                                    } while (readcnt > 0);

                                    if (mem)
                                    {
                                        _Resp = ((MemoryStream)streamd).ToArray();
                                    }
                                }
                                finally
                                {
                                    stream.Dispose();
                                    if (streamd != null)
                                    {
                                        if (streamd != _DestStream)
                                        {
                                            streamd.Dispose();
                                        }
                                    }
                                }
                            }
                        }
                        finally
                        {
#if NETFX_CORE
                            resp.Dispose();
#else
                            resp.Close();
#endif
                        }
                    }
                }
                catch (TimeoutException te)
                {
                    if (GLog.IsLogErrorEnabled)
                    {
                        GLog.LogException(te);
                    }
                    _Error = "timedout";
                }
                catch (System.Net.WebException we)
                {
                    if (GLog.IsLogErrorEnabled)
                    {
                        GLog.LogException(we);
                    }
#if NETFX_CORE
                    if (we.Status.ToString() == "Timeout")
#else
                    if (we.Status == System.Net.WebExceptionStatus.Timeout)
#endif
                    {
                        _Error = "timedout";
                    }
                    else
                    {
                        if (we.Response is System.Net.HttpWebResponse && ((System.Net.HttpWebResponse)we.Response).StatusCode == System.Net.HttpStatusCode.RequestedRangeNotSatisfiable)
                        {
                        }
                        else
                        {
                            _Error = "Request Error (Exception):\n" + we.ToString();
                        }
                    }
                }
                catch (Exception e)
                {
                    if (GLog.IsLogErrorEnabled)
                    {
                        GLog.LogException(e);
                    }
                    _Error = "Request Error (Exception):\n" + e.ToString();
                }
                finally
                {
                    if (_Error == null)
                    {
                        lock (_CloseLock)
                        {
                            _Closed   = true;
                            _InnerReq = null;
                        }
                    }
                    else
                    {
                        StopRequest();
                    }
                }
            }
            catch (TimeoutException te)
            {
                if (GLog.IsLogErrorEnabled)
                {
                    GLog.LogException(te);
                }
                _Error = "timedout";
            }
            catch (System.Net.WebException we)
            {
                if (GLog.IsLogErrorEnabled)
                {
                    GLog.LogException(we);
                }
#if NETFX_CORE
                if (we.Status.ToString() == "Timeout")
#else
                if (we.Status == System.Net.WebExceptionStatus.Timeout)
#endif
                {
                    _Error = "timedout";
                }
                else
                {
                    _Error = "Request Error (Exception):\n" + we.ToString();
                }
            }
            catch (Exception e)
            {
                if (GLog.IsLogErrorEnabled)
                {
                    GLog.LogException(e);
                }
                _Error = "Request Error (Exception):\n" + e.ToString();
            }
            finally
            {
                lock (_CloseLock)
                {
                    _Status = RequestStatus.Finished;
                    if (_OnDone != null)
                    {
                        var ondone = _OnDone;
                        _OnDone = null;
                        ondone();
                    }
                }
            }
        }
Пример #25
0
        public static int ClrFuncApkLoader(IntPtr l)
        {
            var oldtop = l.gettop();

            if (UnityFramework.ResManager.LoadAssetsFromApk)
            {
                string mname = l.GetString(1);
                if (!string.IsNullOrEmpty(mname))
                {
                    mname = mname.Replace('.', '/');
                    int retryTimes = 10;
                    for (int i = 0; i < retryTimes; ++i)
                    {
                        System.Exception error = null;
                        do
                        {
                            Unity.IO.Compression.ZipArchive za = UnityFramework.ResManager.AndroidApkZipArchive;
                            if (za == null)
                            {
                                error = new Exception("Apk Archive Cannot be read.");
                                break;
                            }
                            try
                            {
                                bool done   = false;
                                var  dflags = Capstones.UnityFramework.ResManager.GetDistributeFlags();
                                for (int j = dflags.Length - 1; j >= 0; --j)
                                {
                                    var flag      = dflags[j];
                                    var entryname = "assets/spt/distribute/" + flag + "/" + mname + ".lua";
                                    var entry     = za.GetEntry(entryname);
                                    if (entry != null)
                                    {
                                        var pathd = AppUpdatePath + "/spt/" + entryname.Substring("assets/spt/".Length);
                                        using (var srcstream = entry.Open())
                                        {
                                            using (var dststream = PlatExt.PlatDependant.OpenWrite(pathd))
                                            {
                                                srcstream.CopyTo(dststream);
                                            }
                                        }

                                        l.loadfile(pathd);
                                        done = true;
                                        break;
                                    }
                                }
                                if (!done)
                                {
                                    var entryname = "assets/spt/" + mname + ".lua";
                                    var entry     = za.GetEntry(entryname);
                                    if (entry != null)
                                    {
                                        var pathd = AppUpdatePath + "/spt/" + entryname.Substring("assets/spt/".Length);
                                        using (var srcstream = entry.Open())
                                        {
                                            using (var dststream = PlatExt.PlatDependant.OpenWrite(pathd))
                                            {
                                                srcstream.CopyTo(dststream);
                                            }
                                        }

                                        l.loadfile(pathd);
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                error = e;
                                break;
                            }
                        } while (false);
                        if (error != null)
                        {
                            if (i == retryTimes - 1)
                            {
                                if (GLog.IsLogErrorEnabled)
                                {
                                    GLog.LogException(error);
                                }
                                throw error;
                            }
                            else
                            {
                                if (GLog.IsLogErrorEnabled)
                                {
                                    GLog.LogException(error + "\nNeed Retry " + i);
                                }
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
            return(l.gettop() - oldtop);
        }
        public static void MoveFile(this string src, string dst)
        {
            if (IsFileSameName(src, dst))
            {
                if (GLog.IsLogInfoEnabled)
                {
                    GLog.LogInfo("Move same file: " + (src ?? "") + " -> " + (dst ?? ""));
                }
                return;
            }

            if (!string.IsNullOrEmpty(src) && !string.IsNullOrEmpty(dst))
            {
                CreateFolder(Path.GetDirectoryName(dst));
                // try to lock src and delete dst.
                {
                    Stream srcfile = null;
                    try
                    {
                        srcfile = OpenRead(src);
                        DeleteFile(dst);
                    }
                    catch (Exception e)
                    {
                        if (GLog.IsLogErrorEnabled)
                        {
                            GLog.LogException(e);
                        }
                    }
                    finally
                    {
                        if (srcfile != null)
                        {
                            srcfile.Dispose();
                        }
                    }
                }
                try
                {
                    File.Move(src, dst);
                }
                catch (Exception e)
                {
                    if (GLog.IsLogErrorEnabled)
                    {
                        GLog.LogException(e);
                    }
                    throw;
                }
            }
            else
            {
                if (string.IsNullOrEmpty(src))
                {
                    if (GLog.IsLogInfoEnabled)
                    {
                        GLog.LogInfo("MoveFile, src is empty");
                    }
                }
                if (string.IsNullOrEmpty(dst))
                {
                    if (GLog.IsLogInfoEnabled)
                    {
                        GLog.LogInfo("MoveFile, dst is empty");
                    }
                }
            }
        }
        /// <summary>
        /// init 操作  默认会去 Path.Combine(Application.persistentDataPath, "GlogCtrl.txt")
        /// 找配置如果找不到 采用 编译配置 方便在出包后动态调整日志输出权限
        /// </summary>
        public static void Init()
        {
            if (_isInit)
            {
                return;
            }
            var logConfigUrl = Path.Combine(Application.persistentDataPath, "GlogCtrl.txt");

            ///如果是编辑器模式 则直接读取 Path.Combine(Application.streamingAssetsPath, "GlogCtrl.txt") 文件
            if (Application.isEditor)
            {
                logConfigUrl = Path.Combine(Application.streamingAssetsPath, "GlogCtrl.txt");
            }
            if (File.Exists(logConfigUrl))
            {
                try
                {
                    using (var sr = OpenReadText(logConfigUrl))
                    {
                        string   item;
                        string[] attr = null;
                        while (!sr.EndOfStream)
                        {
                            item = sr.ReadLine();
                            if (string.IsNullOrEmpty(item) || item.IndexOf("|") == -1)
                            {
                                continue;
                            }
                            attr = item.Split('|');
                            SetGLogProperty(attr[0], attr[1]);
                        }
                    }
                }
                catch (Exception e)
                {
                    if (GLog.IsLogErrorEnabled)
                    {
                        GLog.LogException(e);
                    }
                    goto GlogDefault;
                }
                GLog.Init();
                _isInit = true;
                return;
            }
GlogDefault:
            if (GLog.IsLogInfoEnabled)
            {
                GLog.LogInfo("Glog 编译设置");
            }
#if DISABLE_LOG_ALL
            GLog.SetAllLogEnabled(false);
#endif
#if DISABLE_LOG_INFO
            GLog.SetLogInfoEnabled(false);
#endif
#if DISABLE_LOG_WARN
            GLog.SetLogWarningEnabled(false);
#endif
#if DISABLE_LOG_ERROR
            GLog.SetLogErrorEnabled(false);
#endif
#if DISABLE_LOG_CONSOLE
            GLog.SetLogToConsoleEnabled(false);
#endif
#if DISABLE_LOG_STACKTRACE
            GLog.SetLogStackTraceEnabled(false);
#endif
#if UNITY_IPHONE
            GLog.SetCallLogBack(CallLogBack);
#endif
#if !(DEVELOPMENT_BUILD || UNITY_EDITOR || ALWAYS_SHOW_LOG || DEBUG)
            GLog.SetCallLogBack(null);
            GLog.SetLogToConsoleEnabled(false);
            GLog.SetLogInfoEnabled(false);
            GLog.SetLogStackTraceEnabled(false);
#endif
            GLog.Init();
            _isInit = true;
        }
Пример #28
0
        private void DispatchRecvQueue(ConcurrentQueue <TmpSocketData> recvQueue)
        {
            if (recvQueue == null)
            {
                return;
            }
            bool isShowLog = false;

#if UNITY_EDITOR
            isShowLog = true;
#endif
            try
            {
                while (recvQueue.Count > 0)
                {
                    TmpSocketData data;
                    if (!recvQueue.TryDequeue(out data))
                    {
                        continue;
                    }
                    if (data.protocallType < 10000)
                    {
                        Action <string> handler = NetReceiver.GetHandler(data.protocallType);
                        string          content = Encoding.UTF8.GetString(data.data);
                        if (handler != null)
                        {
                            if (isShowLog && GLog.IsLogInfoEnabled)
                            {
                                GLog.LogInfo("protocallType = " + data.protocallType + ", content = " + content);
                            }
                            handler(content);
                            continue;
                        }
                        if (isShowLog && GLog.IsLogErrorEnabled)
                        {
                            GLog.LogError("The (" + data.protocallType + ") do not have handler!");
                        }
                        continue;
                    }
                    else
                    {
                        Action <byte[]> handler = NetReceiver.GetHandlerByte(data.protocallType);
                        if (handler != null)
                        {
                            if (isShowLog && GLog.IsLogInfoEnabled)
                            {
                                GLog.LogInfo("protocallType = " + data.protocallType);
                            }
                            handler(data.data);
                            continue;
                        }
                        if (isShowLog && GLog.IsLogErrorEnabled)
                        {
                            GLog.LogError("The (" + data.protocallType + ") do not have handler!");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                GLog.LogException("DispatchRecvQueue ==> " + e.Message);
            }
        }