Beispiel #1
0
        public ClientListener(Socket handler, bool isDummy = false)
        {
            maxTryNum             = 3;
            isPrintClose          = false;
            isTryLinking          = false;
            batchNum              = 10;
            receiveQueue          = new ConcurrentQueue <byte[]>();
            waitSendQueue         = new Queue <byte[]>();
            m_headLengthConverter = VUInt32.Instance;
            headBuffer            = new byte[m_headLengthConverter.VTypeLength];
            reserveBuffer         = new byte[RESERVE_SIZE];
            m_baseRpcCallHead     = VUInt16.Instance.Encode(MSGIDType.BASEAPP_CLIENT_RPCALL);
            m_cellRpcCallHead     = VUInt16.Instance.Encode(MSGIDType.BASEAPP_CLIENT_RPC2CELL_VIA_BASE);

            m_isDummy = isDummy;
            if (isDummy)
            {
                return;
            }

            client                   = handler;
            client.NoDelay           = true;  //Negal
            client.SendBufferSize    = 0xfa00;
            client.ReceiveBufferSize = 0xfa00;
            resetWhileConnected();
            startReceive();
            if (netStatusListener != null)
            {
                netStatusListener(LINK_OK);
            }
            timeId = TimerHeap.AddTimer(1000, 3000, closeNotice);                                                                 //连接关闭通知
            sendWaitPack();                                                                                                       //发送由于网络中断的滞留包
        }
Beispiel #2
0
        private void DoReceive()
        {
            //读取流
            do
            {
                bytesRead = 0;
                try
                {
                    int size = MAX_BUFFER_SIZE - m_nRecvBufferSize;
                    if (size > 0)
                    {
                        bytesRead          = m_socket.Receive(m_recvBuffer, m_nRecvBufferSize, size, SocketFlags.None);
                        m_nRecvBufferSize += bytesRead;
                        if (bytesRead == 0)
                        {//读的长度为0
                            bytesRead = 1;
                        }
                    }
                    else
                    {
                        bytesRead = 1;//缓存不够时继续循环,后面会对缓存数据进行处理
                        LoggerHelper.Warning("buffer not enough");
                    }
                }
                catch (ObjectDisposedException)
                {
                    // 网络流已被关闭,结束接收数据
                    LoggerHelper.Error("tcp close");
                }
                catch (IOException ioex)
                {
                    //捕获WSACancelBlockingCall()导致的异常。
                    //原因:强迫终止一个在进行的阻塞调用。
                    //可直接捕获忽略,应该不会有不良影响。
                    //LoggerHelper.Error("WSACancelBlockCall");
                    LoggerHelper.Except(ioex);
                }
                catch (Exception ex)
                {
                    LoggerHelper.Except(ex);
                }
                //LoggerHelper.Debug("DataReceive: " + bytesRead);
                SplitPackets();
            } while (bytesRead > 0);

            lock (m_connectCheckerLocker)
                if (m_ConnectChecker > 0)
                {
                    m_ConnectChecker--;
                    LoggerHelper.Debug("Disconnected.m_ConnectChecker: " + m_ConnectChecker);
                }
                else
                {
                    LoggerHelper.Error("receive bytes " + bytesRead);
                    TimerHeap.AddTimer(1000, 0, OnNetworkDisconnected);
                }

            LoggerHelper.Debug("DataReceiveComplete");
        }
Beispiel #3
0
        public static void GetHttp(string Url, Action <string> onDone, Action <HttpStatusCode> onFail)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            HttpWebRequest  request  = null;
            HttpWebResponse response = null;

            try
            {
                request = (HttpWebRequest)WebRequest.Create(Url);
            }
            catch (Exception)
            {
                onFail(HttpStatusCode.NotAcceptable);
                return;
            }
            stopwatch.Stop();
            uint timerId = TimerHeap.AddTimer(0x3a98, 0, () => onFail(HttpStatusCode.RequestTimeout));

            stopwatch.Start();
            response = (HttpWebResponse)request.GetResponse();
            stopwatch.Stop();
            if (response.StatusCode != HttpStatusCode.OK)
            {
                stopwatch.Start();
                TimerHeap.DelTimer(timerId);
                onFail(response.StatusCode);
                stopwatch.Stop();
            }
            else
            {
                TimerHeap.DelTimer(timerId);
                stopwatch.Start();
                Stream responseStream = response.GetResponseStream();
                stopwatch.Stop();
                stopwatch.Start();
                Encoding      encoding = Encoding.UTF8;
                StreamReader  reader   = new StreamReader(responseStream, encoding);
                char[]        buffer   = new char[0x100];
                int           length   = reader.Read(buffer, 0, 0x100);
                StringBuilder builder  = new StringBuilder("");
                while (length > 0)
                {
                    string str = new string(buffer, 0, length);
                    builder.Append(str);
                    length = reader.Read(buffer, 0, 0x100);
                }
                stopwatch.Stop();
                stopwatch.Start();
                response.Close();
                reader.Close();
                stopwatch.Stop();
                stopwatch.Start();
                onDone(builder.ToString());
                stopwatch.Stop();
            }
        }
Beispiel #4
0
        private static void LoadCreateRequestAssets(List <Resource> list, MonoBehaviour mono, Action loaded)
        {
            //var resources = new List<Resource>();
            //foreach (var res in list)
            //{
            //    if (res.IsDone || res.IsLoading)
            //        continue;
            //    var path = WithSuffix(res.RelativePath);
            //    var fileName = String.Concat(SystemConfig.ResourceFolder, path);
            //    res.fileData = Utils.LoadByteFile(fileName);//FileAccessManager.LoadBytes(path);
            //    if (res.fileData != null && res.fileData.Length != 0)
            //        resources.Add(res);
            //    else
            //        Debug.LogError("Load file failure: " + path);
            //}
            //mono.StartCoroutine(DoLoadCreateRequestAssets(resources, loaded));
            var resources = new List <Resource>();

            foreach (var res in list)
            {
                if (res.IsDone)
                {
                    continue;
                }
                resources.Add(res);
            }
            Action action = () =>
            {
                var loadedResources = new List <Resource>();
                foreach (var res in resources)
                {
                    var path = WithSuffix(res.RelativePath);
                    //var fileName = String.Concat(SystemConfig.ResourceFolder, path);
                    //res.fileData = Utils.LoadByteFile(fileName);//FileAccessManager.LoadBytes(path);
                    res.fileData = FileAccessManager.LoadBytes(path);
                    if (res.fileData != null && res.fileData.Length != 0)
                    {
                        loadedResources.Add(res);
                    }
                    else
                    {
                        Debug.LogError("Load file failure: " + path);
                    }
                }
                TimerHeap.AddTimer(0, 0, () => mono.StartCoroutine(DoLoadCreateRequestAssets(loadedResources, loaded)));
            };

#if UNITY_IPHONE
            action();
#else
            action.BeginInvoke(null, null);
#endif
        }
Beispiel #5
0
 private void DoReceive()
 {
     do
     {
         this.bytesRead = 0;
         try
         {
             int size = 0xffff - this.m_nRecvBufferSize;
             if (size > 0)
             {
                 this.bytesRead          = this.m_socket.Receive(this.m_recvBuffer, this.m_nRecvBufferSize, size, SocketFlags.None);
                 this.m_nRecvBufferSize += this.bytesRead;
                 if (this.bytesRead == 0)
                 {
                     this.bytesRead = 1;
                 }
             }
             else
             {
                 this.bytesRead = 1;
                 LoggerHelper.Warning("buffer not enough", true);
             }
         }
         catch (ObjectDisposedException)
         {
             LoggerHelper.Error("tcp close", true);
         }
         catch (IOException exception)
         {
             LoggerHelper.Except(exception, null);
         }
         catch (Exception exception2)
         {
             LoggerHelper.Except(exception2, null);
         }
         this.SplitPackets();
     }while (this.bytesRead > 0);
     lock (this.m_connectCheckerLocker)
     {
         if (this.m_ConnectChecker > 0)
         {
             this.m_ConnectChecker--;
             LoggerHelper.Debug("Disconnected.m_ConnectChecker: " + this.m_ConnectChecker, true, 0);
         }
         else
         {
             LoggerHelper.Error("receive bytes " + this.bytesRead, true);
             TimerHeap.AddTimer(0x3e8, 0, this.OnNetworkDisconnected);
         }
     }
     LoggerHelper.Debug("DataReceiveComplete", true, 0);
 }
Beispiel #6
0
        public void GetTimeFromServer()
        {
            second++;
            escapeSecond++;

            curSyncTime++;
            dateTime = defaultFixServerTime.AddMinutes(timeZone).AddSeconds(second);
            EventDispatcher.TriggerEvent(Events.OtherEvent.SecondPast);
            if (curSyncTime >= defalutSyncTime)
            {
                curSyncTime = 0;
                MogoWorld.thePlayer.GetServerTimeStampReq();
            }
            timer = TimerHeap.AddTimer(1000, 0, GetTimeFromServer);
        }
Beispiel #7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="datastr"></param>
        /// <returns>返回字符串</returns>
        public static void SendPostHttp(string Url, string datastr, Action <string> onDone, Action <HttpStatusCode> onFail)
        {
            byte[] data = System.Text.Encoding.UTF8.GetBytes(datastr);
            // 准备请求...
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Url);

            req.Method        = "Post"; //Getor Post
            req.ContentType   = "application/x-www-form-urlencoded";
            req.ContentLength = data.Length;
            Stream stream = req.GetRequestStream();

            // 发送数据
            stream.Write(data, 0, data.Length);
            stream.Close();

            uint            timerId = TimerHeap.AddTimer(15000, 0, () => { onFail(HttpStatusCode.RequestTimeout); });
            HttpWebResponse rep     = (HttpWebResponse)req.GetResponse();


            if (rep.StatusCode != HttpStatusCode.OK)
            {
                TimerHeap.DelTimer(timerId);
                onFail(rep.StatusCode);
            }
            else
            {
                TimerHeap.DelTimer(timerId);
                Stream   receiveStream = rep.GetResponseStream();
                Encoding encode        = System.Text.Encoding.UTF8;
                // Pipes the stream to a higher level stream reader with the required encoding format.
                StreamReader readStream = new StreamReader(receiveStream, encode);

                Char[]        read  = new Char[256];
                int           count = readStream.Read(read, 0, 256);
                StringBuilder sb    = new StringBuilder("");
                while (count > 0)
                {
                    String readstr = new String(read, 0, count);
                    sb.Append(readstr);
                    count = readStream.Read(read, 0, 256);
                }

                rep.Close();
                readStream.Close();

                onDone(sb.ToString());
            }
        }
Beispiel #8
0
        /// <summary>
        /// 默认构造函数。
        /// </summary>
        public LogWriter()
        {
#if !UNITY_WEBPLAYER
            if (Application.isEditor || Application.platform == RuntimePlatform.WindowsPlayer)
            {
                m_logPath = SystemConfig.PCPath + "/log/";
            }
            if (!Directory.Exists(m_logPath))
            {
                Directory.CreateDirectory(m_logPath);
            }
            m_logFilePath = String.Concat(m_logPath, String.Format(m_logFileName, DateTime.Today.ToString("yyyyMMdd")));
            try
            {
                //m_logWriter = Write;
                m_fs            = new FileStream(m_logFilePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                m_sw            = new StreamWriter(m_fs);
                initFileSuccess = true;
#endif
            if (Application.platform == RuntimePlatform.IPhonePlayer)
            {
                TimerHeap.AddTimer(10, 20, DoWrite);
            }
            else
            {
                if (m_thread == null)
                {
                    m_thread = new Thread(WriteLogHandler);
                    m_thread.Start();
                }
            }
#if !UNITY_WEBPLAYER
        }

        catch (Exception ex)
        {
            initFileSuccess = false;
            UnityEngine.Debug.LogError("init file error:" + ex.Message);
        }
#endif
        }
Beispiel #9
0
 private void onConnected(IAsyncResult ar)
 {
     try
     {
         isConnecting = false;
         resetWhileConnected();
         client.EndConnect(ar);
         startReceive();
         if (netStatusListener != null)
         {
             netStatusListener(LINK_OK);
         }
         timeId = TimerHeap.AddTimer(1000, 3000, closeNotice);                                                                 //连接关闭通知
         sendWaitPack();                                                                                                       //发送由于网络中断的滞留包
     }
     catch (Exception ex)
     {
         LoggerHelper.Error("-connect() 连接服务器[" + ip + ":" + port + "]失败,reason:" + ex.ToString());
         tryConnect();
     }
 }
Beispiel #10
0
        public static void SendPostHttp(string Url, string datastr, Action <string> onDone, Action <HttpStatusCode> onFail)
        {
            byte[]         bytes   = Encoding.UTF8.GetBytes(datastr);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);

            request.Method        = "Post";
            request.ContentType   = "application/x-www-form-urlencoded";
            request.ContentLength = bytes.Length;
            Stream requestStream = request.GetRequestStream();

            requestStream.Write(bytes, 0, bytes.Length);
            requestStream.Close();
            uint            timerId  = TimerHeap.AddTimer(0x3a98, 0, () => onFail(HttpStatusCode.RequestTimeout));
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            if (response.StatusCode != HttpStatusCode.OK)
            {
                TimerHeap.DelTimer(timerId);
                onFail(response.StatusCode);
            }
            else
            {
                TimerHeap.DelTimer(timerId);
                Stream        responseStream = response.GetResponseStream();
                Encoding      encoding       = Encoding.UTF8;
                StreamReader  reader         = new StreamReader(responseStream, encoding);
                char[]        buffer         = new char[0x100];
                int           length         = reader.Read(buffer, 0, 0x100);
                StringBuilder builder        = new StringBuilder("");
                while (length > 0)
                {
                    string str = new string(buffer, 0, length);
                    builder.Append(str);
                    length = reader.Read(buffer, 0, 0x100);
                }
                response.Close();
                reader.Close();
                onDone(builder.ToString());
            }
        }
Beispiel #11
0
        public static void GetHttp(string Url, Action <string> onDone, Action <HttpStatusCode> onFail)
        {
            //Debug.LogError("GetHttp");
            // 准备请求...
            System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
            stopWatch.Start();
            HttpWebRequest  req = null;
            HttpWebResponse rep = null;

            try
            {
                req = (HttpWebRequest)WebRequest.Create(Url);
            }
            catch (Exception e)
            {
                //Debug.LogError(e.ToString());
                onFail(HttpStatusCode.NotAcceptable);
                return;
            }

            stopWatch.Stop();
            //Debug.LogError("req Create:" + stopWatch.ElapsedMilliseconds);

            uint timerId = TimerHeap.AddTimer(15000, 0, () => { onFail(HttpStatusCode.RequestTimeout); });

            stopWatch.Start();
            rep = (HttpWebResponse)req.GetResponse();
            stopWatch.Stop();
            //Debug.LogError("req GetResponse:" + stopWatch.ElapsedMilliseconds);

            if (rep.StatusCode != HttpStatusCode.OK)
            {
                stopWatch.Start();
                TimerHeap.DelTimer(timerId);
                onFail(rep.StatusCode);
                stopWatch.Stop();
                //Debug.LogError("req onFail:" + stopWatch.ElapsedMilliseconds);
            }
            else
            {
                TimerHeap.DelTimer(timerId);
                stopWatch.Start();
                Stream receiveStream = rep.GetResponseStream();
                stopWatch.Stop();
                //Debug.LogError("req GetResponseStream:" + stopWatch.ElapsedMilliseconds);

                stopWatch.Start();
                Encoding encode = System.Text.Encoding.UTF8;
                // Pipes the stream to a higher level stream reader with the required encoding format.
                StreamReader readStream = new StreamReader(receiveStream, encode);

                Char[]        read  = new Char[256];
                int           count = readStream.Read(read, 0, 256);
                StringBuilder sb    = new StringBuilder("");
                while (count > 0)
                {
                    String readstr = new String(read, 0, count);
                    sb.Append(readstr);
                    count = readStream.Read(read, 0, 256);
                }

                stopWatch.Stop();
                //Debug.LogError("req readStream:" + stopWatch.ElapsedMilliseconds);

                stopWatch.Start();
                rep.Close();
                readStream.Close();
                stopWatch.Stop();
                //Debug.LogError("req Close:" + stopWatch.ElapsedMilliseconds);


                stopWatch.Start();
                onDone(sb.ToString());
                stopWatch.Stop();
                //Debug.LogError("req onDone:" + stopWatch.ElapsedMilliseconds);
            }
        }
Beispiel #12
0
 public void GetEscapeTimeFromServer()
 {
     MogoWorld.thePlayer.GetServerTimeEscapeReq();
     escapeTimer = TimerHeap.AddTimer(30000, 0, GetTimeFromServer);
 }