예제 #1
0
        protected void ReadFromStream()
        {
            if (_netStream.CanRead)
            {
                try
                {
                    int length = _netStream.Read(_recBuf, _recBufOffset, _recBuf.Length - _recBufOffset);
                    _recBufOffset += length;

                    if (length == 0)
                    {
                        FLog.Debug("NetStream.Read length = 0");
                        if (_fOnReceiveFail != null)
                        {
                            _fOnReceiveFail();
                        }
                        SetTerminateFlag();
                    }
                }
                catch (Exception ex)
                {
                    FLog.Error("ReceiverThread Exception:" + ex.ToString());
                    if (_fOnReceiveFail != null)
                    {
                        _fOnReceiveFail();
                    }
                    SetTerminateFlag();
                }
            }
            else
            {
                Thread.Sleep(16);
            }
        }
예제 #2
0
        /// <summary>
        /// 非线程安全,只允许在主线程调用
        /// </summary>
        public void AttachListenerNow(IEventListener listener, uint eventKey)
        {
            if (listener == null)
            {
                FLog.Error("AttachListenerNow failed due to no listener or event key specified in EventDispacher.");
                return;
            }

            if (System.Threading.Thread.CurrentThread.ManagedThreadId != 1)
            {
                FLog.Debug("AttachListenerNow -> " + eventKey);
            }
            if (!_listenerHashTable.ContainsKey(eventKey))
            {
                _listenerHashTable.Add(eventKey, new ArrayList());
            }

            ArrayList listenerList = _listenerHashTable[eventKey] as ArrayList;

            if (listenerList.Contains(listener))
            {
                FLog.Error("AttachListenerNow -> " + listener.GetType().ToString() + " is already in list for event: " + eventKey.ToString() + " in EventDispacher.");
                return;
            }

            AttachListner(eventKey, listenerList, listener);
        }
예제 #3
0
        public static bool SaveToXml <T>(string filePath, T source) where T : class
        {
            if (source == null)
            {
                FLog.Debug("SaveToXml() failed, source is null.");
                return(false);
            }

            if (!File.Exists(filePath))
            {
                FLog.Debug("SaveToXml() filePath is not existed, create file: " + filePath.ToString());
                File.Create(filePath);
            }

            try
            {
                using (StreamWriter writer = new StreamWriter(filePath))
                {
                    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
                    xmlSerializer.Serialize(writer, source);
                }
            }
            catch (Exception ex)
            {
                FLog.Debug("SaveToXml() " + ex.ToString());
                return(false);
            }
            return(true);
        }
예제 #4
0
        void CloseTcpClient()
        {
            if (_tcpClient == null)
            {
                FLog.Debug("CloseTcpClient already");
                return;
            }

            if (_tcpClient.Connected)
            {
                try
                {
                    _tcpClient.GetStream().Close();
                }
                catch (Exception ex)
                {
                    FLog.Debug("CloseTcpClient Stream Close exception: " + ex.ToString());
                }
            }

            try
            {
                _tcpClient.Close();
            }
            catch (Exception ex)
            {
                FLog.Debug("CloseTcpClient TcpClient Close exception: " + ex.ToString());
            }

            _tcpClient = null;
        }
예제 #5
0
        void StartConnectThread()
        {
            if (_tcpClient == null)
            {
                _tcpClient                   = new TcpClient();
                _tcpClient.NoDelay           = true;
                _tcpClient.ReceiveBufferSize = TcpClientReceiveBufferSize;
                _tcpClient.ReceiveTimeout    = TcpClientReceiveTimeout;
                _tcpClient.SendBufferSize    = TcpClientSendBufferSize;
                _tcpClient.SendTimeout       = TcpClientSendTimeout;
            }

            _connecter = new ConnectThread(_tcpClient, _NetHostName, _Port, delegate(bool bOK)
            {
                FLog.Debug("ConnectThread Callback: " + bOK.ToString());
                if (bOK)
                {
                    _taskExecutor.Add(ConnectOK);
                }
                else
                {
                    _taskExecutor.Add(ConnectFail);
                }

                if (_connecter != null)
                {
                    _connecter.ClearCallback();
                    _connecter = null;
                }
            });
            _connecter.Run();
        }
예제 #6
0
        void ConnectFail()
        {
            FLog.Debug("ConnectFail");

            if (NetState == NETSTATE.Connecting)
            {
                NetState = NETSTATE.ConnectFailed;
                RemoveConnectTimer();
                if (--_retryTimes > 0)
                {
                    CloseTcpClient();
                    BeginRetryTimer();
                }
                else
                {
                    CloseConnect();

                    if (netConnectionCallback != null)
                    {
                        netConnectionCallback(NETEVENT.RetryFail);
                    }
                }
            }
            else
            {
                FLog.Debug("ConnnectFail ignore, NetState = " + NetState.ToString());
            }
        }
예제 #7
0
        protected override void Main()
        {
            FLog.Debug("ConnectThread.Main: Begin");

            try
            {
                _tcpClient.Connect(_hostName, _port);
                if (_fCallback != null)
                {
                    _fCallback(true);
                }
            }
            catch (ObjectDisposedException ex)
            {
                FLog.Debug("Connect ObjectDisposedException: " + ex.Message);
            }
            catch (Exception ex)
            {
                FLog.Debug("Connect Exception: " + ex.Message);
                if (_fCallback != null)
                {
                    _fCallback(false);
                }
            }

            FLog.Debug("ConnectThread.Main: End");
        }
예제 #8
0
        public static void SaveDictToTxt(Dictionary <string, int> dic, string filePath, string title = "")
        {
            if (string.IsNullOrEmpty(filePath) || dic == null)
            {
                return;
            }

            StringBuilder sb = new StringBuilder();

            sb.AppendLine(title + "\n");
            foreach (KeyValuePair <string, int> kvp in dic)
            {
                sb.AppendLine(kvp.Value.ToString() + ", " + kvp.Key.Substring(0, kvp.Key.LastIndexOf('.')));
            }
            sb.AppendLine("\nLength = " + dic.Count.ToString());
            sb.AppendLine(DateTime.Now.ToString("yy-MM-dd HH:mm:ss"));

            try
            {
                using (StreamWriter writer = new StreamWriter(File.Open(filePath, FileMode.Create)))
                {
                    writer.Write(sb.ToString());
                }
            }
            catch (Exception ex)
            {
                FLog.Debug("SaveDictionaryToTxt() " + ex.Message);
            }
        }
예제 #9
0
        public static bool LoadDictFromFile(Dictionary <int, int> dict, string filePath)
        {
            if (!File.Exists(filePath) || dict == null)
            {
                return(false);
            }

            try
            {
                using (BinaryReader reader = new BinaryReader(File.Open(filePath, FileMode.Open)))
                {
                    Stream stream = reader.BaseStream;
                    long   length = stream.Length;
                    while (stream.Position < length)
                    {
                        int dictKey   = reader.ReadInt32();
                        int dictValue = reader.ReadInt32();

                        dict[dictKey] = dictValue;
                    }
                }
            }
            catch (Exception ex)
            {
                FLog.Debug("LoadDictFromFile() " + ex.Message);
                return(false);
            }

            return(true);
        }
예제 #10
0
        public static bool LoadListFromFile(List <string> list, string filePath)
        {
            if (!File.Exists(filePath) || list == null)
            {
                return(false);
            }

            try
            {
                using (BinaryReader reader = new BinaryReader(File.Open(filePath, FileMode.Open)))
                {
                    Stream stream = reader.BaseStream;
                    long   length = stream.Length;
                    while (stream.Position < length)
                    {
                        string msg = reader.ReadString();
                        if (msg != null)
                        {
                            list.Add(msg);
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                FLog.Debug("LoadListFromFile() " + ex.Message);
                return(false);
            }

            return(true);
        }
예제 #11
0
        public static bool LoadFromXml <T>(string filePath, out T result) where T : class
        {
            result = null;

            if (!File.Exists(filePath))
            {
                FLog.Debug("LoadFromXml() failed, filePath is not existed.");
                return(false);
            }

            try
            {
                using (StreamReader reader = new StreamReader(filePath))
                {
                    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
                    result = xmlSerializer.Deserialize(reader) as T;
                }
            }
            catch (Exception ex)
            {
                FLog.Debug("LoadFromXml() " + ex.ToString());
                return(false);
            }
            return(true);
        }
예제 #12
0
        /// <summary>
        /// 非线程安全,只允许在主线程调用
        /// </summary>
        public void DetachListenerNow(IEventListener listener, uint eventKey)
        {
            if (listener == null)
            {
                FLog.Error("DetachListenerNow failed due to no listener or event key specified in EventDispacher.");
                return;
            }

            if (System.Threading.Thread.CurrentThread.ManagedThreadId != 1)
            {
                FLog.Debug("DetachListenerNow -> " + eventKey);
            }
            if (!_listenerHashTable.ContainsKey(eventKey))
            {
                return;
            }

            ArrayList listenerList = _listenerHashTable[eventKey] as ArrayList;

            if (!listenerList.Contains(listener))
            {
                return;
            }

            listenerList.Remove(listener);
        }
예제 #13
0
 void BeginConnectTimer()
 {
     _connectTimerId = TimerManager.instance.SetTimeout(delegate(long id, object p1, object p2)
     {
         FLog.Debug("ConnectTimeout");
         ConnectTimeout();
     }, TcpConnectTimeout);
 }
예제 #14
0
 void ConnectServer(string strIP, int nPort)
 {
     FLog.Debug("ConnectServer: " + strIP.ToString() + ":" + nPort.ToString());
     CloseConnect();
     _Port = nPort;
     EnableRetry(true);
     StartConnecting();
 }
예제 #15
0
 void CheckReConnect()
 {
     if (NetState == NETSTATE.DisConnected && !IsNotReachable() && _retryTimes > 0)
     {
         FLog.Debug("CheckReConnect, Connecting");
         StartConnecting();
     }
 }
예제 #16
0
 void BeginRetryTimer()
 {
     _retryTimerId = TimerManager.instance.SetTimeout(delegate(long id, object p1, object p2)
     {
         FLog.Debug("RetryTimes = " + _retryTimes.ToString());
         StartConnecting();
     }, 0.3f);
 }
예제 #17
0
        private void Quit()
        {
            FLog.Debug("Application.Quit()");
#if UNITY_EDITOR
            UnityEditor.EditorApplication.isPlaying = false;
#else
            Application.Quit();
#endif
        }
예제 #18
0
        void StopConnectServer()
        {
            FLog.Debug("StopConnectServer");
            _stopped = true;
            CloseConnect();
            EnableRetry(false);

            RemoveConnectTimer();
            RemoveRetryTimer();
            _taskExecutor.Clear();
        }
예제 #19
0
        protected override void Main()
        {
            FLog.Debug("ReceiverThread.Main: Begin");

            while (!IsTerminateFlagSet())
            {
                ReadFromStream();
                ScanPackets();
            }

            FLog.Debug("ReceiverThread.Main: End");
        }
예제 #20
0
 void ConnectServer()
 {
     if (NetState == NETSTATE.Init || NetState == NETSTATE.DisConnected)
     {
         _stopped = false;
         ConnectServer(_NetHostName, _Port);
     }
     else
     {
         FLog.Debug("ConnectServer Error: NetState = " + NetState.ToString());
     }
 }
        void OnDestroy()
        {
            if (!GameManager.instance.IsAppQuit())
            {
                FLog.Debug("DestroyEventTrigger -> OnDestroy()");
                if (onDestroy != null)
                {
                    onDestroy(gameObject);
                }
            }

            parent = null;
        }
예제 #22
0
        void NotifyDisConnect()
        {
            FLog.Debug("NotifyDisConnect");

            if (NetState == NETSTATE.Connected)
            {
                CloseConnect();
            }
            else
            {
                FLog.Debug("NotifyDisConnect NetState = " + NetState.ToString());
            }
        }
예제 #23
0
 void StartReceiveThread()
 {
     if (_tcpClient == null)
     {
         return;
     }
     _receiver = new ReceiverThread(_tcpClient.GetStream(), EnqueueRespondMsg, delegate()
     {
         FLog.Debug("ReceiveThread Callback");
         _taskExecutor.Add(NotifyDisConnect);
     });
     _receiver.Run();
 }
예제 #24
0
        protected override void Main()
        {
            FLog.Debug("SenderThread.Main: Begin");

            while (!IsTerminateFlagSet())
            {
                bool   sleep   = false;
                byte[] _buffer = null;

                lock (_msgToSend)
                {
                    if (_msgToSend.Count > 0)
                    {
                        _buffer = _msgToSend[0];
                    }
                    else
                    {
                        sleep = true;
                    }
                }

                if (_buffer != null)
                {
                    try
                    {
                        _netStream.Write(_buffer, 0, _buffer.Length);
                        _netStream.Flush();
                    }
                    catch (Exception ex)
                    {
                        FLog.Error(string.Format("SenderThead, Main Write Exception, {0}, {1}, {2}", ex.Message, ex.StackTrace, ex.InnerException.Message));
                    }

                    lock (_msgToSend)
                    {
                        if (_msgToSend.Count > 0)
                        {
                            _msgToSend.RemoveAt(0);
                        }
                    }
                }

                if (sleep)
                {
                    Thread.Sleep(15);
                }
            }

            FLog.Debug("SenderThread.Main: End");
        }
예제 #25
0
        public void AttachListener <T>(IEventListener listener, T eventId, bool bIsAttach = true)
        {
            int idx = 0;
            FEventDispatcher evtDispatcher = GetByEventTypeName(typeof(T).FullName, ref idx);

            if (evtDispatcher != null)
            {
                evtDispatcher.AttachListenerNow(listener, Convert.ToUInt32(eventId), bIsAttach);
            }
            else
            {
                FLog.Error("Error event type: " + typeof(T).FullName);
            }
        }
예제 #26
0
        public static byte[] LoadBytesFromFile(string filePath)
        {
            if (!File.Exists(filePath))
            {
                return(null);
            }

            try
            {
                return(File.ReadAllBytes(filePath));
            }
            catch (Exception ex)
            {
                FLog.Debug("LoadBytesFromFile() " + ex.Message);
                return(null);
            }
        }
예제 #27
0
        public static void SaveToJpg(Texture2D texture, string filePath, bool destroyTexture = false)
        {
            if (texture == null)
            {
                FLog.Debug("SaveToJpg() failed, texture is null.");
                return;
            }

            byte[] png = texture.EncodeToJPG();
            SaveBytesToFile(png, filePath);
            if (destroyTexture)
            {
                Texture2D.DestroyImmediate(texture);
            }
            png = null;

            FLog.Debug("SaveToJpg() succeed.");
        }
예제 #28
0
        void StartConnecting()
        {
            if (NetState == NETSTATE.ConnectFailed || NetState == NETSTATE.DisConnected)
            {
                NetState = NETSTATE.Connecting;
                if (netConnectionCallback != null)
                {
                    netConnectionCallback(NETEVENT.Connecting);
                }

                BeginConnectTimer();
                StartConnectThread();
            }
            else
            {
                FLog.Debug("StartConnecting ignore, NetState=" + NetState.ToString());
            }
        }
예제 #29
0
 void ConnectTimeout()
 {
     if (_tcpClient != null && !_tcpClient.Connected)
     {
         FLog.Debug("BeginConnect Timeout, Close socket");
         CloseTcpClient();
         if (_connecter != null)
         {
             _connecter.ClearCallback();
             _connecter = null;
         }
         ConnectFail();
     }
     else
     {
         FLog.Debug("BeginConnect m_tcpClient is connected");
     }
 }
예제 #30
0
        public T AddPopUp <T>(string prefabName, bool mode = true, string id = null, bool isBringForward = true, float maskAlpha = MASK_ALPHA, bool canRemove = true)
        {
            GameObject popup = AddPopUp((GameObject)Resources.Load(prefabName as string), mode, id, isBringForward, maskAlpha, canRemove);

            if (popup != null)
            {
                T ret = popup.GetComponent <T>();
                if (ret == null)
                {
                    FLog.Debug("Can't Find Type: " + typeof(T).ToString());
                    RemovePopUp(popup);
                }
                else
                {
                    return(ret);
                }
            }
            return(default(T));
        }