Пример #1
0
        private void Run()
        {
            //...建立接收的位置, 所有
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            //...返回對方的位置
            EndPoint remoteEP = (EndPoint)(sender);

            try
            {
                while (true)
                {
                    _allDone.Reset();
                    UDPServerStateObject stateObject = new UDPServerStateObject();
                    stateObject.workSocket    = _socket;
                    stateObject.receiveBuffer = new byte[_receiveBuffer];
                    _socket.BeginReceiveFrom(stateObject.receiveBuffer, 0, _receiveBuffer, 0, ref remoteEP, new AsyncCallback(ReceiveFromCallback), stateObject);
                    _allDone.WaitOne();
                }
            }
            catch (Exception ex)
            {
                _allDone.Set();
                KConsole.Write(ErrorLevel.Serious, "Kernel>>AsynUDPServer>>Run", ex.Message);
            }
        }
Пример #2
0
        private void SendCallback(IAsyncResult ar)
        {
            //try
            //{
            //    int bytesSent = tcpClient.EndSend(ar);
            //    //sendDone.Set();
            //}
            //catch (Exception ex)
            //{
            //    //sendDone.Set();
            //    this._connected = false;
            //    KConsole.Write(ErrorLevel.Serious, "Kernel>>AsynTCPClient>>SendCallback>>", ex.Message);
            //}
            int bytesSent = 0;

            try
            {
                if (!tcpClient.Connected)
                {
                    return;
                }
                if (tcpClient == null)
                {
                    return;
                }
                bytesSent = tcpClient.EndSend(ar);
            }
            catch (Exception ex)
            {
                this._connected = false;
                tcpClient       = null;
                KConsole.Write(ErrorLevel.Response, "", "KoIPRouter>>AsynTCPClient>>SendCallback>>Exception:" + ex.Message);
                //KConsole.Write(ErrorLevel.Serious, "Kernel>>StateObject>>SendCallback", ex.Message);
            }
        }
Пример #3
0
        public static string Createdir(string directoryName)
        {
            try
            {
                if (OSType != 0)
                {
                    directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase).Remove(0, 6) + "\\" + directoryName;
                }
                else
                {
                    directoryName = "./" + directoryName;
                }

                DirectoryInfo Createdir = new DirectoryInfo(directoryName);
                if (!Createdir.Exists)
                {
                    Createdir.Create();
                }
                return(directoryName);
            }
            catch (Exception ex)
            {
                KConsole.Write(ErrorLevel.Serious, "Kernel>>Tools>>Createdir", ex.Message);
                return(null);
            }
        }
Пример #4
0
        public void BeginConnect(string Address, int Port)
        {
            try
            {
                _targetAddress = Address;
                _targetPort    = Port;
                remoteEP       = new IPEndPoint(System.Net.IPAddress.Parse(_targetAddress), _targetPort);
                tcpClient      = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                Thread listen = new Thread(new ThreadStart(Run));
                listen.Start();

                //...等待連線成功
                while (!this._connected)
                {
                    Thread.Sleep(500);
                }
            }
            catch (Exception ex)
            {
                connectDone.Set();
                KConsole.Write(ErrorLevel.Serious, "Kernel>>AsynTCPClient>>Start", ex.Message);
                //GC.Collect();
                //throw new ArgumentNullException();
            }
        }
Пример #5
0
 public void Stop()
 {
     try
     {
         if (_listenerSocket != null)
         {
             try
             {
                 _listenerSocket.Shutdown(SocketShutdown.Both);
             }
             catch { }
             _listenerSocket.Close(3000);
         }
         //if (_listenerSocket!=null)
         //{
         //    _listenerSocket.Shutdown(SocketShutdown.Both);
         //}
     }
     catch (Exception ex)
     {
         KConsole.Write(ErrorLevel.Response, "", "Kernel>>AsynTCPSocket>>Stop>>Exception:" + ex.Message);
         //KConsole.Write(ErrorLevel.Serious, "Kernel>>AsynTCPSocket>>Stop", ex.Message);
         throw new ArgumentNullException();
     }
     finally
     {
         _listenerSocket = null;
         //GC.Collect();
     }
 }
Пример #6
0
        public static void SaveSerialize(string filePath, byte[] buffer, int count)
        {
            try
            {
                if (string.IsNullOrEmpty(filePath))
                {
                    KConsole.Write(ErrorLevel.Warn, "Kernel>>DiskIO>>SaveSerialize", "filePath is null or empty");
                    throw new ArgumentNullException();
                }

                using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    using (BinaryWriter bw = new BinaryWriter(fs))
                    {
                        bw.Write(buffer, 0, count);
                        bw.Flush();
                    }
                }
            }
            catch (Exception ex)
            {
                KConsole.Write(ErrorLevel.Serious, "Kernel>>DiskIO>>SaveSerialize", ex.Message);
                throw new ArgumentNullException();
            }
        }
Пример #7
0
        public static void Del(object _obj)
        {
            try
            {
                if (_obj == null)
                {
                    KConsole.Write(ErrorLevel.Serious, "Kernel>>DiskIO>>Del", "_obj無效");
                    return;
                }

                string   _filepath = (string)_obj;
                FileInfo file      = new FileInfo(_filepath);
                if (file.Exists)
                {
                    file.Delete();
                }
                file = null;
                //GC.Collect(0);
            }
            catch (Exception ex)
            {
                KConsole.Write(ErrorLevel.Serious, "Kernel>>DiskIO>>Save", ex.Message);
                //throw new ArgumentNullException();
            }
        }
Пример #8
0
        //<summary>
        //產生ConnectID ,隨機 []Byte  自己帶整數
        //</summary>
        public static string createSession(int seed)
        {
            RNGCryptoServiceProvider rng = null;

            byte[] random = null;
            try
            {
                //...隨機產生ConnectID
                random = new Byte[seed];
                rng    = new RNGCryptoServiceProvider();
                rng.GetNonZeroBytes(random);
                return(Convert.ToBase64String(random).Replace("/", "").Replace("\\", "").Replace(":", "").Replace("?", "").Replace("<", "").Replace(">", "").Replace("|", "").Replace("*", "").Replace("\"", ""));
            }
            catch (Exception ex)
            {
                KConsole.Write(ErrorLevel.Serious, "Kernel>>RandomSession>>getSession", ex.Message);
                throw new ArgumentNullException();
            }
            finally
            {
                rng    = null;
                random = null;
                //GC.Collect(0);
            }
        }
Пример #9
0
        public void Start()
        {
            try
            {
                //if (string.IsNullOrEmpty(_listenerAddress))
                //{
                //    //KConsole.Write(ErrorLevel.Serious, "Kernel>>AsynTCPSocket>>Start", "_listenerAddress is null");
                //    KConsole.Write(ErrorLevel.Response, "", "Kernel>>AsynTCPSocket>>Start: _listenerAddress is null");
                //    throw new ArgumentNullException();
                //}

                if (_listenerPort <= 0)
                {
                    KConsole.Write(ErrorLevel.Response, "", "Kernel>>AsynTCPSocket>>Start: _listenerPort <=0");
                    throw new ArgumentNullException();
                }
                IPEndPoint localEndPoint = null;
                if (string.IsNullOrEmpty(_listenerAddress))
                {
                    localEndPoint = new IPEndPoint(System.Net.IPAddress.Any, listenerPort);
                }
                else
                {
                    localEndPoint = new IPEndPoint(System.Net.IPAddress.Parse(listenerAddress), listenerPort);
                }
                _listenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                #region 端口复用 modify by whr 20100911未启用
                /*端口复用 modify by whr 20100911*/
                //try
                //{
                //    _listenerSocket.Bind(localEndPoint);
                //}
                //catch
                //{
                //    _listenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //    _listenerSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                //    _listenerSocket.Bind(localEndPoint);
                //    //return;
                //}
                /**********************************/
                #endregion

                _listenerSocket.Bind(localEndPoint);
                KConsole.Write(ErrorLevel.Response, "", "Kernel>>AsynTCPSocket>>Start>>Bind  the socket  and Listen>>" + _listenerAddress + ":" + listenerPort.ToString());
                _listenerSocket.Listen(_pendingConnectionsQueue);
                KConsole.Write(ErrorLevel.Response, "", "pendingConnectionsQueue: " + _pendingConnectionsQueue.ToString());
                Thread listen = new Thread(new ParameterizedThreadStart(Run));
                listen.Start(_listenerSocket);
            }
            catch (Exception ex)
            {
                KConsole.Write(ErrorLevel.Response, "", "Kernel>>AsynTCPSocket>>Start>>Exception:" + ex.Message);
                //KConsole.Write(ErrorLevel.Serious, "Kernel>>AsynTCPSocket>>Start", ex.Message);
                _listenerSocket = null;
                //GC.Collect();
                //throw new ArgumentNullException();
            }
        }
Пример #10
0
        public void Start()
        {
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            _socket.Bind(_ipLocalEndPoint);
            KConsole.Write(ErrorLevel.Debug, "AsynUDPServer>>Start>>Listen:", ((EndPoint)_ipLocalEndPoint).ToString());
            Thread listen = new Thread(new ThreadStart(Run));

            listen.Start();
        }
Пример #11
0
 /// <summary>
 /// 將Base64 Chars 還原ASCII bytes  還原 String
 /// </summary>
 public static string FromBase64Chars(char[] srcData)
 {
     try
     {
         return(Encoding.ASCII.GetString(Convert.FromBase64CharArray(srcData, 0, srcData.Length)));
     }
     catch (Exception ex)
     {
         KConsole.Write(ErrorLevel.Serious, "Kernel>>Tools>>FromBase64Chars>>", ex.Message);
         return(null);
     }
 }
Пример #12
0
 /// <summary>
 /// 將String轉成ASCII bytes 轉成 Base64 String
 /// </summary>
 public static string ToBase64String(string srcData)
 {
     try
     {
         return(Convert.ToBase64String(Encoding.ASCII.GetBytes(srcData)));
     }
     catch (Exception ex)
     {
         KConsole.Write(ErrorLevel.Response, "", "Kernel>>Tools>>ToBase64String>>Exception:" + ex.Message);
         return(null);
     }
 }
Пример #13
0
 /// <summary>
 /// 將String轉成ASCII bytes 轉成 Base64 Chars
 /// </summary>
 public static char[] ToBase64Chars(string srcData)
 {
     try
     {
         char[] charData = Convert.ToBase64String(Encoding.ASCII.GetBytes(srcData)).ToCharArray();
         return(charData);
     }
     catch (Exception ex)
     {
         KConsole.Write(ErrorLevel.Response, "", "Kernel>>Tools>>ToBase64Chars>>Exception :" + ex.Message);
         return(null);
     }
 }
Пример #14
0
 public void BeginSendTo(byte[] buffer)
 {
     _sendToDone.Reset();
     try
     {
         _workSocket.BeginSendTo(buffer, 0, buffer.Length, 0, _tempRemoteEP, new AsyncCallback(SendToCallback), null);
     }
     catch (Exception ex)
     {
         KConsole.Write(ErrorLevel.Serious, "Kernel>>UDPServerStateObject>>BeginSendTo>>", ex.Message);
     }
     _sendToDone.WaitOne();
 }
Пример #15
0
        /// <summary>
        /// Gzip壓縮
        /// </summary>
        public static int GzipCompress(ref byte[] srcBuffer, ref byte[] cmpBuffer)
        {
            string _CompressSaveFilePath = null;

            try
            {
                string directoryName = "";
                if (OSType != 0)
                {
                    directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase).Remove(0, 6) + "\\Compress\\";
                }
                else
                {
                    directoryName = "./" + "Compress/";
                }

                DirectoryInfo Createdir = new DirectoryInfo(directoryName);
                if (!Createdir.Exists)
                {
                    Createdir.Create();
                }

                _CompressSaveFilePath = directoryName + RandomSession.createSession(64);

                using (FileStream fs_saveCompress = new FileStream(_CompressSaveFilePath, FileMode.Create, FileAccess.Write))
                {
                    using (GZipStream ZipStream = new GZipStream(fs_saveCompress, CompressionMode.Compress, true))
                    {
                        ZipStream.Write(srcBuffer, 0, srcBuffer.Length);
                    }
                }

                using (FileStream fs_open = new FileStream(_CompressSaveFilePath, FileMode.Open, FileAccess.Read))
                {
                    cmpBuffer = new byte[Convert.ToInt32(fs_open.Length)];
                    fs_open.Read(cmpBuffer, 0, Convert.ToInt32(fs_open.Length));
                }

                return(1);
            }
            catch (Exception ex)
            {
                KConsole.Write(ErrorLevel.Serious, "Kernel>>Tools>>GzipCompress>>", ex.Message);
                return(0);
            }
            finally
            {
                DiskIO.Del(_CompressSaveFilePath);
            }
        }
Пример #16
0
 /// <summary>
 ///將來源字串 轉成 指定編碼
 /// </summary>
 public static Byte[] StringEncodingConver(string srcData, Encoding srcEncoding, Encoding tgaEncoding)
 {
     try
     {
         Byte[] _srcBytes = srcEncoding.GetBytes(srcData);
         Byte[] _dstBytes = Encoding.Convert(srcEncoding, tgaEncoding, _srcBytes);
         return(_dstBytes);
     }
     catch (Exception ex)
     {
         KConsole.Write(ErrorLevel.Serious, "Kernel>>Tools>>StringEncodingConver>>", ex.Message);
         return(null);
     }
 }
Пример #17
0
 public static StateObject Deserialize(byte[] _serializeBuffe)
 {
     try
     {
         using (MemoryStream ms_open_SerializePackage = new MemoryStream(_serializeBuffe))
         {
             BinaryFormatter formatter = new BinaryFormatter();
             return((StateObject)formatter.Deserialize(ms_open_SerializePackage));
         }
     }
     catch (Exception ex)
     {
         KConsole.Write(ErrorLevel.Serious, "Kernel>>Tools>>Deserialize", ex.Message);
         return(null);
     }
 }
Пример #18
0
 private void ConnectCallback(IAsyncResult ar)
 {
     try
     {
         tcpClient.EndConnect(ar);
         KConsole.Write(ErrorLevel.Debug, "Kernel>>AsynTCPClient>>Run>>", "連接>>" + tcpClient.RemoteEndPoint.ToString());
         //connectDone.Set();
         this._connected = true;
     }
     catch (Exception ex)
     {
         //connectDone.Set();
         this._connected = false;
         KConsole.Write(ErrorLevel.Serious, "Kernel>>AsynTCPClient>>Run>>", ex.Message);
     }
 }
Пример #19
0
 public static byte[] Serialize(StateObject obj)
 {
     try
     {
         using (MemoryStream ms_save_SerializePackage = new MemoryStream())
         {
             BinaryFormatter formatter = new BinaryFormatter();
             formatter.Serialize(ms_save_SerializePackage, obj);
             return(ms_save_SerializePackage.ToArray());
         }
     }
     catch (Exception ex)
     {
         KConsole.Write(ErrorLevel.Serious, "Kernel>>Tools>>Serialize", ex.Message);
         return(null);
     }
 }
        public void AcceptCallback(IAsyncResult ar)
        {
            StateObject state = null;

            try
            {
                Socket server  = (Socket)ar.AsyncState;
                Socket newUser = server.EndAccept(ar); //...建立一個對應的連接
                //...設定接收及傳送的緩衝區
                //newUser.ReceiveBufferSize = 32768;
                //newUser.SendBufferSize = 32768;
                //...建立一個保存連線狀態的物件
                state = new StateObject();
                state.headerBufferSize = 9;       //...設定封包讀取大小
                state.workSocket       = newUser; //...連接進來的線路
                state.receiveBuffer    = new byte[state.headerBufferSize];

                //string wanip = state.wanIP;
                //string wanport = state.wanPort.ToString();
                //KConsole.Write(ErrorLevel.Debug, "Kernel>>AsynTCPSocket>>AcceptCallback>>連接進來的連線>>", wanip + ":" + wanport);

                // 每一條連接進來的請求都建立ConnectionSession
                string ConnectionSession = RandomSession.createSession(32);
                state.ConnectionSession = ConnectionSession;
                KConsole.Write(ErrorLevel.Response, "", "Kernel>>AsynTCPSocket>>AcceptCallback>>ConnectionSession:" + ConnectionSession);
                //KConsole.Write(ErrorLevel.Debug, "Kernel>>AsynTCPSocket>>AcceptCallback>>建立ConnectionSession>>", ConnectionSession);
                _allDone.Set();
                //...開始接收請求 ,先接收封包的標頭
                newUser.BeginReceive(state.receiveBuffer, 0, state.headerBufferSize, 0, new AsyncCallback(ReadCallback), state);
            }
            catch (Exception ex)
            {
                _allDone.Set();
                _allDone.Reset();
                KConsole.Write(ErrorLevel.Response, "", "Kernel>>AsynTCPSocket>>AcceptCallback>>Exception:" + ex.Message);
                //KConsole.Write(ErrorLevel.Serious, "Kernel>>AsynTCPSocket>>AcceptCallback>>", ex.Message);

                if (state != null)
                {
                    ExceptionHandlingEvent(state);
                    state = null;
                    GC.Collect();
                }
            }
        }
Пример #21
0
 private void BeginReceive()
 {
     try
     {
         //receiveDone.Reset();
         TCPClientStateObject state = new TCPClientStateObject();
         state.headerBufferSize = 9;
         state.receiveBuffer    = new byte[state.headerBufferSize];
         state.workSocket       = tcpClient;
         tcpClient.BeginReceive(state.receiveBuffer, 0, state.headerBufferSize, 0, new AsyncCallback(ReceiveCallback), state);
         //receiveDone.WaitOne();
     }
     catch (Exception ex)
     {
         this._connected = false;
         KConsole.Write(ErrorLevel.Serious, "Kernel>>AsynTCPClient>>BeginReceive>>", ex.Message);
     }
 }
Пример #22
0
 public void Stop()
 {
     try
     {
         if (tcpClient != null)
         {
             tcpClient.Close();
         }
     }
     catch (Exception ex)
     {
         KConsole.Write(ErrorLevel.Serious, "Kernel>>AsynTCPClient>>Stop", ex.Message);
     }
     finally
     {
         tcpClient = null;
         GC.Collect();
     }
 }
Пример #23
0
 public static void SaveToMemory(char[] srcBuffer, ref byte[] targetBuffer, Encoding encoding)
 {
     try
     {
         using (MemoryStream ms = new MemoryStream())
         {
             using (StreamWriter sw = new StreamWriter(ms, encoding))
             {
                 sw.Write(srcBuffer);
                 sw.Flush();
             }
             targetBuffer = ms.ToArray();
         }
     }
     catch (Exception ex)
     {
         KConsole.Write(ErrorLevel.Serious, "Kernel>>DiskIO>>SaveToMemory", ex.Message);
     }
 }
Пример #24
0
        //public string userLoginID
        //{
        //    get
        //    {
        //        return this._userLoginID;
        //    }
        //    set
        //    {
        //        this._userLoginID = value;
        //    }
        //}

        //public SortedList userTable
        //{
        //    get
        //    {
        //        return this._userTable;
        //    }
        //    set
        //    {
        //        this._userTable = value;
        //    }
        //}

        //public string roomID
        //{
        //    get
        //    {
        //        return this._roomID;
        //    }
        //    set
        //    {
        //        this._roomID = value;
        //    }
        //}

        //public SortedList roomTable
        //{
        //    get
        //    {
        //        return this._roomTable;
        //    }
        //    set
        //    {
        //        this._roomTable = value;
        //    }
        //}

        //public string roomLineName
        //{
        //    get
        //    {
        //        return this._roomLineName;
        //    }
        //    set
        //    {
        //        this._roomLineName = value;
        //    }
        //}

        public void Send(byte[] data)
        {
            try
            {
                if (_workSocket == null)
                {
                    return;
                }
                if (!_workSocket.Connected)
                {
                    return;
                }

                this.workSocket.BeginSend(data, 0, data.Length, 0, new AsyncCallback(SendCallback), null);
            }
            catch (Exception ex)
            {
                KConsole.Write(ErrorLevel.Serious, "Kernel>>StateObject>>Send", ex.Message);
            }
        }
Пример #25
0
        private void SendCallback(IAsyncResult ar)
        {
            int bytesSent = 0;

            try
            {
                if (_workSocket == null)
                {
                    return;
                }
                if (!_workSocket.Connected)
                {
                    return;
                }
                bytesSent = _workSocket.EndSend(ar);
            }
            catch (ObjectDisposedException ex)
            {
                KConsole.Write(ErrorLevel.Serious, "Kernel>>StateObject>>SendCallback", ex.Message);
            }
        }
Пример #26
0
        public void BeginSend(byte[] buffer)
        {
            ////sendDone.Reset();
            //tcpClient.BeginSend(buffer, 0, buffer.Length, 0, new AsyncCallback(SendCallback), null);
            ////sendDone.WaitOne();


            try
            {
                if (tcpClient == null)
                {
                    return;
                }
                //KConsole.Write(ErrorLevel.Response, "", "KoIPRouter>>AsynTCPClient>>BeginSend>>Exception:" + tcpClient.Connected);

                if (!tcpClient.Connected)
                {
                    return;
                }

                this.tcpClient.BeginSend(buffer, 0, buffer.Length, 0, new AsyncCallback(SendCallback), null);
            }
            catch (Exception ex)
            {
                KConsole.Write(ErrorLevel.Response, "", "KoIPRouter>>AsynTCPClient>>BeginSend>>Exception:" + ex.Message);
                //try
                //{
                //    tcpClient.Shutdown(SocketShutdown.Both);
                //}
                //catch
                //{
                //    tcpClient.Close();
                //}
                this._connected = false;
                tcpClient       = null;
                // KConsole.Write(ErrorLevel.Serious, "Kernel>>StateObject>>Send", ex.Message);
            }
        }
Пример #27
0
        private void ReceiveFromCallback(IAsyncResult ar)
        {
            try
            {
                UDPServerStateObject so = (UDPServerStateObject)ar.AsyncState;
                Socket socket           = so.workSocket;

                IPEndPoint sender             = new IPEndPoint(IPAddress.Any, 0);
                EndPoint   tempRemoteEP       = (EndPoint)sender;
                int        receivedDataLength = socket.EndReceiveFrom(ar, ref tempRemoteEP);
                so.tempRemoteEP = tempRemoteEP;

                ReceiveEvent(so);//...交由外部處理
            }
            catch (Exception ex)
            {
                KConsole.Write(ErrorLevel.Serious, "Kernel>>AsynUDPServer>>ReceiveFromCallback", ex.Message);
            }
            finally
            {
                _allDone.Set();
            }
        }
Пример #28
0
 public void Send(byte[] data)
 {
     try
     {
         if (!_workSocket.Connected)
         {
             return;
         }
         if (_workSocket == null)
         {
             return;
         }
         _allDone.Set();
         this.workSocket.BeginSend(data, 0, data.Length, 0, new AsyncCallback(SendCallback), null);
         _allDone.WaitOne();
     }
     catch (Exception ex)
     {
         //_workSocket.Shutdown(SocketShutdown.Both);
         KConsole.Write(ErrorLevel.Response, "", "KoIPRouter>>StateObject>>Send>>Exception:" + ex.Message);
         // KConsole.Write(ErrorLevel.Serious, "Kernel>>StateObject>>Send", ex.Message);
     }
 }
        public void ReadCallback(IAsyncResult ar)
        {
            StateObject state       = null;
            bool        closeSocket = false;

            try
            {
                state = (StateObject)ar.AsyncState;
                Socket userClient = state.workSocket;
                int    bytesRead  = 0;

                //...判斷socket連線是否斷掉
                if (userClient == null || !userClient.Connected)
                {
                    closeSocket = true;
                    return;
                }

                bytesRead = userClient.EndReceive(ar);



                if (bytesRead > 0)
                {
                    #region//...是否讀過 Header
                    if (!state.isReadHeader)
                    {
                        //...建立接收封包的存放位置
                        //string directoryName = "/"+Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase).Remove(0, 6) + "/Process/";
                        string directoryName = "./Process/";

                        if (OSType != 0)
                        {
                            directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase).Remove(0, 6) + "\\Process\\";
                        }
                        DirectoryInfo Createdir = new DirectoryInfo(directoryName);
                        if (!Createdir.Exists)
                        {
                            Createdir.Create();
                        }
                        //state.receiveFileTemporarily = directoryName + RandomSession.createSession(64);
                        state.receiveFileTemporarily = directoryName + Guid.NewGuid();

                        using (MemoryStream ms_readheader = new MemoryStream(state.receiveBuffer, 0, bytesRead))
                        {
                            BinaryReader br = new BinaryReader(ms_readheader);
                            state.ver  = br.ReadByte();                     //...封包版本號
                            state.cmd1 = br.ReadInt16();                    //...命令1
                            state.cmd2 = br.ReadInt16();                    //...命令2
                            state.receivePackageTotalSize = br.ReadInt32(); //...封包內容總長度

                            if (state.receivePackageTotalSize <= 0)
                            {
                                //...沒有夾帶內容
                                state.isReadHeader           = false;                            //...讀取完畢將標記改為false
                                state.receiveBuffer          = null;
                                state.receiveBuffer          = new byte[state.headerBufferSize]; //...Buffer 清空
                                state.receiveFileTemporarily = null;
                                GoToProcess(state);                                              //...接收完畢號 處理事件
                            }
                            else
                            {
                                //...當有夾帶內容時
                                state.receiveBuffer = null;
                                state.receiveBuffer = new byte[state.receivePackageTotalSize]; //... 080609 by randy
                                state.isReadHeader  = true;                                    //,,,將標記設定為讀過標頭,可以繼續接收資料
                            }
                        }

                        //...接收buffer的資料
                        if (userClient == null || !userClient.Connected)
                        {
                            closeSocket = true;
                            return;
                        }

                        userClient.BeginReceive(state.receiveBuffer, 0, state.receiveBuffer.Length, 0, new AsyncCallback(ReadCallback), state);
                        return;
                    }
                    #endregion

                    #region //...儲存數據

                    DiskIO.Save(state.receiveFileTemporarily, state.receiveBuffer, bytesRead);


                    state.receivePackageTotalSize = state.receivePackageTotalSize - bytesRead;//--randy,2008.06.09
                    if (state.receivePackageTotalSize == 0)
                    {
                        //...接收完畢
                        state.isReadHeader  = false;                            //...讀取Header reset
                        state.receiveBuffer = new byte[state.headerBufferSize]; //...recevice buffer reset
                        GoToProcess(state);                                     //...接收完畢號 處理事件
                    }
                    else if (state.receivePackageTotalSize > 0)
                    {
                        //...繼續接收
                        state.receiveBuffer = new byte[state.receivePackageTotalSize];//--randy,2008.06.09
                    }
                    #endregion

                    #region//...接收buffer的資料
                    //...接收buffer的資料
                    if (userClient == null || !userClient.Connected)
                    {
                        closeSocket = true;
                        return;
                    }
                    userClient.BeginReceive(state.receiveBuffer, 0, state.receiveBuffer.Length, 0, new AsyncCallback(ReadCallback), state);

                    #endregion
                }
                else
                {
                    //KConsole.Write(ErrorLevel.Response, "", "Kernel>>AsynTCPSocket>>ReadCallback>>Exception: 接收到的數據長度<=0");
                    //KConsole.Write(ErrorLevel.Warn, "Kernel>>AsynTCPSocket>>ReadCallback>>", "接收到的數據長度<=0");
                    closeSocket = true;
                }
            }
            catch (Exception ex)
            {
                //KConsole.Write(ErrorLevel.Serious, "Kernel>>AsynTCPSocket>>ReadCallback>>", ex.Message);
                KConsole.Write(ErrorLevel.Response, "", "Kernel>>AsynTCPSocket>>ReadCallback>>Exception:" + ex.Message);
                closeSocket = true;
            }
            finally
            {
                if (closeSocket)
                {
                    if (ExceptionHandlingEvent != null)
                    {
                        ExceptionHandlingEvent(state);
                    }
                    state = null;
                    GC.Collect();
                }
            }
        }
Пример #30
0
        public void ReceiveCallback(IAsyncResult ar)
        {
            //TCPClientStateObject state1 = null;
            TCPClientStateObject state = null;
            bool closeSocket           = false;

            try
            {
                state = (TCPClientStateObject)ar.AsyncState;
                //MsgBackQue.Enqueue(state1);
                //object obj = MsgBackQue.Dequeue();
                //state = (TCPClientStateObject)obj;
                Socket userClient = state.workSocket;
                int    bytesRead  = 0;

                //...判斷socket連線是否斷掉
                if (userClient == null || !userClient.Connected)
                {
                    closeSocket = true;
                    return;
                }

                bytesRead = userClient.EndReceive(ar);



                if (bytesRead > 0)
                {
                    #region//...是否讀過 Header
                    if (!state.isReadHeader)
                    {
                        //...建立接收封包的存放位置
                        string directoryName = "/" + Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase).Remove(0, 6) + "/Process/";

                        if (OSType != 0)
                        {
                            directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase).Remove(0, 6) + "\\Process\\";
                        }
                        DirectoryInfo Createdir = new DirectoryInfo(directoryName);
                        if (!Createdir.Exists)
                        {
                            Createdir.Create();
                        }
                        //state.receiveFileTemporarily = directoryName + RandomSession.createSession(64);
                        state.receiveFileTemporarily = directoryName + "cli_" + Guid.NewGuid().ToString();

                        byte[] HeadReceiveBuffer = new byte[bytesRead];
                        Array.Copy(state.receiveBuffer, HeadReceiveBuffer, bytesRead);
                        state.ListHeadBuffer.AddRange(HeadReceiveBuffer);
                        state.headerBufferSize = state.headerBufferSize - bytesRead;

                        if (state.headerBufferSize == 0)
                        {
                            state.headerBufferSize = 9;
                            byte[] TempHeadReceiveBuffer = state.ListHeadBuffer.ToArray();
                            state.ListHeadBuffer.Clear();
                            using (MemoryStream ms_readheader = new MemoryStream(TempHeadReceiveBuffer, 0, TempHeadReceiveBuffer.Length))
                            {
                                BinaryReader br = new BinaryReader(ms_readheader);
                                state.ver  = br.ReadByte();                     //...封包版本號
                                state.cmd1 = br.ReadInt16();                    //...命令1
                                state.cmd2 = br.ReadInt16();                    //...命令2
                                state.receivePackageTotalSize = br.ReadInt32(); //...封包內容總長度
                            }

                            if (state.receivePackageTotalSize <= 0)
                            {
                                //...沒有夾帶內容
                                state.isReadHeader  = false;                            //...讀取完畢將標記改為false
                                state.receiveBuffer = new byte[state.headerBufferSize]; //...Buffer 清空
                                ReceiveEvent(state);                                    //...接收完畢號 處理事件
                            }
                            else
                            {
                                state.receiveBuffer = new byte[state.receivePackageTotalSize]; //... 080609 by randy
                                state.isReadHeader  = true;                                    //,,,將標記設定為讀過標頭,可以繼續接收資料
                            }
                        }
                        else if (state.headerBufferSize > 0)
                        {
                            //...繼續接收
                            state.receiveBuffer = new byte[state.headerBufferSize];//--randy,2008.06.09
                        }
                        //...接收buffer的資料
                        if (userClient == null || !userClient.Connected)
                        {
                            closeSocket = true;
                            return;
                        }
                        if (userClient.Connected)
                        {
                            userClient.BeginReceive(state.receiveBuffer, 0, state.receiveBuffer.Length, 0, new AsyncCallback(ReceiveCallback), state);
                            return;
                        }
                        else
                        {
                            closeSocket = true;
                            return;
                        }
                    }
                    #endregion

                    #region//...儲存數據

                    DiskIO.Save(state.receiveFileTemporarily, state.receiveBuffer, bytesRead);
                    state.receivePackageTotalSize = state.receivePackageTotalSize - bytesRead;//--randy,2008.06.09
                    if (state.receivePackageTotalSize == 0)
                    {
                        //...接收完畢
                        state.isReadHeader  = false;                            //...讀取Header reset
                        state.receiveBuffer = new byte[state.headerBufferSize]; //...recevice buffer reset
                        ReceiveEvent(state);                                    //...接收完畢號 處理事件
                        //receiveDone.Set();
                    }
                    else if (state.receivePackageTotalSize > 0)
                    {
                        //...繼續接收
                        state.receiveBuffer = new byte[state.receivePackageTotalSize];//--randy,2008.06.09
                    }
                    #endregion

                    #region//...接收buffer的資料
                    //...接收buffer的資料
                    if (userClient.Connected)
                    {
                        userClient.BeginReceive(state.receiveBuffer, 0, state.receiveBuffer.Length, 0, new AsyncCallback(ReceiveCallback), state);
                    }
                    else
                    {
                        this._connected = false;
                        closeSocket     = true;
                    }
                    #endregion
                }
                else
                {
                    KConsole.Write(ErrorLevel.Warn, "Kernel>>AsynTCPClient>>ReadCallback>>", "接收到的數據長度<=0");
                    closeSocket = true;
                }
            }
            catch (Exception ex)
            {
                KConsole.Write(ErrorLevel.Serious, "Kernel>>AsynTCPClient>>ReceiveCallback>>", ex.Message);
                this._connected = false;
                closeSocket     = true;
            }
            finally
            {
                if (closeSocket)
                {
                    if (ExceptionHandlingEvent != null)
                    {
                        ExceptionHandlingEvent(state);
                    }
                    //receiveDone.Set();
                    state = null;
                    //GC.Collect();
                }
            }
        }