void EndReadCallback(IAsyncResult ar)
        {
            try
            {
                //var stateea = (CtkNonStopTcpStateEventArgs)ar.AsyncState;
                var myea   = (CtkNonStopTcpStateEventArgs)ar.AsyncState;
                var client = myea.workClient;
                if (!ar.IsCompleted || client == null || client.Client == null || !client.Connected)
                {
                    myea.Message = "Read Fail";
                    return;
                }

                var           ctkBuffer = myea.TrxMessageBuffer;
                NetworkStream stream    = client.GetStream();
                int           bytesRead = stream.EndRead(ar);
                ctkBuffer.Length = bytesRead;
                //呼叫他人不應影響自己運作, catch起來
                try { this.OnDataReceive(myea); }
                catch (Exception ex) { CtkLog.Write(ex); }
                stream.BeginRead(ctkBuffer.Buffer, 0, ctkBuffer.Buffer.Length, new AsyncCallback(EndReadCallback), myea);
            }
            catch (IOException ex) { CtkLog.Write(ex); }
            catch (Exception ex) { CtkLog.Write(ex); }
        }
        public void Disconnect()
        {
            if (this.threadNonStopConnect != null)
            {
                this.threadNonStopConnect.Abort();
            }

            foreach (var tc in this.TcpClientList)
            {
                if (tc == null)
                {
                    continue;
                }
                try { tc.Close(); }
                catch (Exception ex) { CtkLog.Write(ex); }
            }

            if (this.m_tcpListener != null)
            {
                this.m_tcpListener.Stop();
            }

            //一旦結束就死了, 需要重new, 所以清掉event沒問題
            CtkEventUtil.RemoveEventHandlersFromOwningByFilter(this, (dlgt) => true);
        }
Ejemplo n.º 3
0
        public List <SNetSignalTransEventArgs> AnalysisSignal <T>(object sender, object msg, IList <T> infos)
        {
            var result  = new List <SNetSignalTransEventArgs>();
            var secsMsg = msg as CxHsmsMessage;

            try
            {
                var list = secsMsg.rootNode as CxSecsIINodeList;

                for (int idx = 0; idx < list.Data.Count; idx++)
                {
                    var ea = new SNetSignalTransEventArgs();
                    ea.Sender = sender;
                    var data = list.Data[idx] as CxSecsIINodeASCII;
                    if (data.Data.Count <= 0)
                    {
                        continue;
                    }

                    ea.Data = new List <double>();
                    ea.Data.Add(double.Parse(data.GetString()));

                    //this.OnDataTrigger(ea);
                    result.Add(ea);
                }
                return(result);
            }
            catch (Exception ex) { CtkLog.Write(ex); }

            return(null);
        }
Ejemplo n.º 4
0
        public int CfLoad()
        {
            CtkThreadingUtil.RunWorkerAsyn(delegate(object sender, DoWorkEventArgs e)
            {
                for (int idx = 0; !this.disposed; idx++)
                {
                    try
                    {
                        hsmsConnector.ConnectIfNo();
                    }
                    catch (Exception ex)
                    {
                        CtkLog.Write(ex);
                        System.Threading.Thread.Sleep(5000);//無法連線等待5秒
                    }


                    try
                    {
                        hsmsConnector.ReceiveRepeat();
                    }
                    catch (Exception ex)
                    {
                        CtkLog.Write(ex);
                        System.Threading.Thread.Sleep(5000);//無法連線等待5秒
                    }
                    finally { System.Threading.Thread.Sleep(1000); }
                }
            });
            return(0);
        }
Ejemplo n.º 5
0
 void DisposeSelf()
 {
     try { this.Disconnect(); }
     catch (Exception ex) { CtkLog.Write(ex); }
     //斷線不用清除Event, 但Dispsoe需要, 因為即使斷線此物件仍存活著
     CtkEventUtil.RemoveEventHandlersOfOwnerByFilter(this, (dlgt) => true);
 }
        public void CleanUntilLast()
        {
            var sourceList = this.m_tcpClientList;

            try
            {
                Monitor.TryEnter(sourceList, 1000);
                var       list   = new List <TcpClient>();
                TcpClient client = null;


                while (!sourceList.IsEmpty)
                {
                    if (!sourceList.TryDequeue(out client))
                    {
                        break;
                    }
                    if (sourceList.IsEmpty)
                    {
                        list.Add(client);
                    }
                    else
                    {
                        CtkNetUtil.DisposeTcpClient(client);
                    }
                }

                foreach (var tc in list)
                {
                    sourceList.Enqueue(tc);
                }
            }
            catch (Exception ex) { CtkLog.Write(ex); }
            finally { Monitor.Exit(sourceList); }
        }
Ejemplo n.º 7
0
        public int CfRunLoopStart()
        {
            //還在執行中, 不接受重新執行
            if (this.RunningTask != null && this.RunningTask.Status < TaskStatus.RanToCompletion)
            {
                return(1);
            }

            //需要重複確認機台的功能是活著的, 因此使用RunLoop重複運作
            this.RunningTask = CtkTask.RunLoop(() =>
            {
                try
                {
                    this.CfRunOnce();
                }
                catch (Exception ex)
                {
                    //Task root method 需要try/catch: 已經到最上層, 就必須捕抓->寫log, 否則就看不到這個例外
                    CtkLog.WriteNs(this, ex);
                }
                Thread.Sleep(5 * 1000);
                return(!this.disposed);//d20201210 機台仍舊要持續運作
            });

            return(0);
        }
        public void CleanDisconnect()
        {
            try
            {
                Monitor.TryEnter(this.TcpClientList, 1000);
                var       list   = new List <TcpClient>();
                TcpClient client = null;
                while (!this.TcpClientList.IsEmpty)
                {
                    if (!this.TcpClientList.TryDequeue(out client))
                    {
                        break;
                    }
                    if (client.Client != null && client.Connected)
                    {
                        list.Add(client);
                    }
                    else
                    {
                        CtkNetUtil.DisposeTcpClient(client);
                    }
                }

                foreach (var tc in list)
                {
                    this.m_tcpClientList.Enqueue(tc);
                }
            }
            catch (Exception ex) { CtkLog.Write(ex); }
            finally { Monitor.Exit(this.TcpClientList); }
        }
Ejemplo n.º 9
0
        public virtual int CfRunLoop()
        {
            this.CfIsRunning = true;
            try
            {
                //三個方法(三個保護)控管執行
                while (!disposed && this.CfIsRunning)
                {
                    if (taskRun != null)
                    {
                        if (this.taskRun.CancelToken.IsCancellationRequested)
                        {
                            break;
                        }
                        this.taskRun.CancelToken.ThrowIfCancellationRequested();//一般cancel task 在 while 和 第一行
                    }
                    this.CfRunOnce();
                }


                CtkLog.Info("Finish SensorDevice");
            }
            catch (Exception ex) { CtkLog.Write(ex, CtkLoggerEnumLevel.Error); }
            return(0);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Remember use stream.Flush() to force data send, Tcp Client always write data into buffer.
        /// </summary>
        /// <param name="buff"></param>
        /// <param name="offset"></param>
        /// <param name="length"></param>
        public void WriteBytes(byte[] buff, int offset, int length)
        {
            if (this.MyTcpClient == null)
            {
                return;
            }
            if (!this.MyTcpClient.Connected)
            {
                return;
            }


            try
            {
                var stm = this.MyTcpClient.GetStream();
                stm.Write(buff, offset, length);
                stm.Flush();
            }
            catch (Exception ex)
            {
                //資料寫入錯誤, 普遍是斷線造成, 先中斷連線清除資料
                this.Disconnect();
                CtkLog.WarnNs(this, ex);
            }
            //stm.BeginWrite(buff, offset, length, new AsyncCallback((ar) =>
            //{
            //    //CtkLog.WriteNs(this, "" + ar.IsCompleted);
            //}), this);
        }
Ejemplo n.º 11
0
 public ComplexD[] FftForwardJustD(ComplexD[] input)
 {
     try
     {
         return(this.CudafyContext.FftForward(input));
     }
     catch (CtkCudafyCannotUseException ex)
     {
         IsUseCudafy = false;
         CtkLog.WarnNs(this, ex.StackTrace);
     }
     catch (Cudafy.CudafyCompileException ex)
     {
         IsUseCudafy = false;
         CtkLog.WarnNs(this, ex.StackTrace);
     }
     catch (System.ComponentModel.Win32Exception ex)
     {
         IsUseCudafy = false;
         CtkLog.WarnNs(this, ex.StackTrace);
     }
     catch (NotSupportedException ex)
     {
         IsUseCudafy = false;
         CtkLog.WarnNs(this, ex.StackTrace);
     }
     return(null);
 }
Ejemplo n.º 12
0
 public void Command(string cmd)
 {
     switch (cmd)
     {
     case "state":
         CtkLog.InfoNs(this, this.CmdState());
         break;
     }
 }
 void DisposeSelf()
 {
     try
     {
         this.Disconnect();
         //一旦結束就死了, 需要重new, 所以清掉event沒問題
         CtkEventUtil.RemoveEventHandlersOfOwnerByFilter(this, (dlgt) => true);
     }
     catch (Exception ex) { CtkLog.Write(ex); }
 }
Ejemplo n.º 14
0
        public void TestMethod()
        {
            CtkLog.RegisterEveryLogWrite((ss, ee) =>
            {
                System.Diagnostics.Debug.WriteLine(ee.Message);
            });

            var deviceHdl = new SNetDvcSensorHandler();

            deviceHdl.Config = new SNetDvcSensorCfg()
            {
                RemoteUri       = "tcp://192.168.123.201:5000",
                TxInterval      = 0,
                TimeoutResponse = 5000,
                ProtoConnect    = SNetEnumProtoConnect.Tcp,
                ProtoFormat     = SNetEnumProtoFormat.SNetCmd,
                ProtoSession    = SNetEnumProtoSession.SNetCmd,
                SignalTran      = SNetEnumSignalTrans.SNetCmd,
            };
            for (var idx = 0; idx < 8; idx++)
            {
                deviceHdl.Config.SignalCfgList.Add(new SNetSignalTransCfg()
                {
                    Svid = 0x00010000 + 0x0100 * (ulong)idx,
                    //Svid = 0x00000000,
                });
            }
            for (var idx = 0; idx < 8; idx++)
            {
                deviceHdl.Config.SignalCfgList.Add(new SNetSignalTransCfg()
                {
                    Svid = 0x00020000 + 0x0100 * (ulong)idx,
                    //Svid = 0x00000000,
                });
            }

            deviceHdl.EhSignalCapture += (sender, ea) =>
            {
                fs.Write(ea);
                //if (ea.Data.Count > 0)
                //System.Diagnostics.Debug.WriteLine("{0}={1}", ea.Svid, ea.Data[0]);
            };



            using (deviceHdl)
            {
                deviceHdl.CfInit();
                deviceHdl.CfLoad();
                deviceHdl.CfRunLoop();
                deviceHdl.CfUnLoad();
                deviceHdl.CfFree();
                System.Threading.Thread.Sleep(100);
            }
        }
Ejemplo n.º 15
0
        protected virtual int RealExec()
        {
            try
            {
                if (!SpinWait.SpinUntil(() => !this.CfIsRunning || this.ProtoConn.IsRemoteConnected, 100))
                {
                    Thread.Sleep(1000);
                    return(0);
                }
                if (!this.CfIsRunning)
                {
                    return(0);                  //若不再執行->return 0
                }
                if (this.Config.IsActivelyTx)
                {
                    var ackDataMsg = this.SignalTran.CreateAckMsg(this.Config.SignalCfgList);
                    if (ackDataMsg != null)
                    {
                        this.ProtoConn.WriteMsg(ackDataMsg);
                    }
                }
                else
                {
                    //等待下次要求資料的間隔
                    if (this.Config.TxInterval > 0)
                    {
                        var interval = DateTime.Now - prevAckTime;
                        while (interval.TotalMilliseconds < this.Config.TxInterval)
                        {
                            if (!this.CfIsRunning)
                            {
                                return(0);                  //若不再執行->直接return
                            }
                            var sleep = this.Config.TxInterval - (int)interval.TotalMilliseconds;
                            if (sleep > 0)
                            {
                                Thread.Sleep(sleep);
                            }
                            interval = DateTime.Now - prevAckTime;
                        }
                    }
                    prevAckTime = DateTime.Now;

                    var reqDataMsg = this.SignalTran.CreateDataReqMsg(this.Config.SignalCfgList);
                    this.ProtoConn.WriteMsg(reqDataMsg);
                }


                //收到資料 或 Timeout 就往下走
                this.areMsg.WaitOne(this.Config.TimeoutResponse);
            }
            catch (Exception ex) { CtkLog.Write(ex); }
            return(0);
        }
Ejemplo n.º 16
0
        public void RunAsyn()
        {
            client = new CtkTcpClient("127.0.0.1", 10002);
            client.EhFirstConnect += (ss, ee) => { CtkLog.InfoNs(this, "evtFirstConnect"); };
            client.EhFailConnect  += (ss, ee) => { CtkLog.InfoNs(this, "evtFailConnect"); };
            client.EhErrorReceive += (ss, ee) => { CtkLog.InfoNs(this, "evtErrorReceive"); };
            client.EhDataReceive  += (ss, ee) =>
            {
                CtkLog.InfoNs(this, "evtDataReceive");
            };

            client.NonStopRunStart();
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Clinet Connect End
        /// </summary>
        /// <param name="ar"></param>
        void EndConnectCallback(IAsyncResult ar)
        {
            var myea      = new CtkNonStopTcpStateEventArgs();
            var trxBuffer = myea.TrxMessageBuffer;

            try
            {
                //Lock使用在短碼保護, 例如: 保護一個變數的get/set
                //Monitor使用在保護一段代碼

                Monitor.Enter(this);                 //一定要等到進去
                var state = (CtkTcpSocket)ar.AsyncState;
                state.WorkSocket = state.ConnSocket; //作為Client時, Work = Conn

                var client = state.WorkSocket;
                client.EndConnect(ar);

                myea.Sender     = state;
                myea.WorkSocket = client;
                if (!ar.IsCompleted || client == null || !client.Connected)
                {
                    throw new CtkException("Connection Fail");
                }


                //呼叫他人不應影響自己運作, catch起來
                try { this.OnFirstConnect(myea); }
                catch (Exception ex) { CtkLog.WarnNs(this, ex); }

                if (this.IsAsynAutoReceive)
                {
                    client.BeginReceive(trxBuffer.Buffer, 0, trxBuffer.Buffer.Length, SocketFlags.None, new AsyncCallback(EndReceiveCallback), myea);
                }
            }
            //catch (SocketException ex) { }
            catch (Exception ex)
            {
                //失敗就中斷連線, 清除
                this.Disconnect();
                myea.Message   = ex.Message;
                myea.Exception = ex;
                this.OnFailConnect(myea);
                CtkLog.WarnNs(this, ex);
            }
            finally
            {
                try { this.mreIsConnecting.Set(); /*同步型的, 結束就可以Set*/ }
                catch (ObjectDisposedException) { }
                Monitor.Exit(this);
            }
        }
        public void UpdateFromFolder(string folder = null)
        {
            this.Folder = folder == null ? this.Folder : folder;//Folder不得為空, 所以傳空值就保留原本的

            this.LastUpdate = DateTime.Now;

            //記錄現有的
            var orignalConfigs = new Dictionary <String, Boolean>();

            foreach (var name in this.Keys)
            {
                orignalConfigs[name] = false;
            }

            var di = new DirectoryInfo(this.Folder);

            if (!di.Exists)
            {
                di.Create();
            }
            foreach (var fi in di.GetFiles())
            {
                if (this.Filter != null)
                {
                    if (!Filter(fi.Name))
                    {
                        continue;                  //沒通過就不加入
                    }
                }
                try
                {
                    var config = CtkUtil.LoadXmlFromFileOrDefault <T>(fi.FullName);
                    this[fi.Name] = config;
                }
                catch (Exception ex) { CtkLog.WriteNs(this, ex.Message); }

                //更新存在的
                orignalConfigs[fi.Name] = true;
            }


            //移除沒更新到的
            foreach (var kv in orignalConfigs)
            {
                if (kv.Value)
                {
                    continue;
                }
                this.Remove(kv.Key);
            }
        }
Ejemplo n.º 19
0
 public int CfRunOnce()
 {
     try
     {
         hsmsConnector.ConnectTry();
         hsmsConnector.ReceiveLoop();
     }
     catch (Exception ex)
     {
         CtkLog.Write(ex);
     }
     finally { System.Threading.Thread.Sleep(1000); }
     return(0);
 }
Ejemplo n.º 20
0
        public int CfRunLoop()
        {
            this.CfIsRunning = true;
            while (!this.disposed && this.CfIsRunning)
            {
                try
                {
                    this.CfRunOnce();
                    Thread.Sleep(1000);
                }
                catch (Exception ex) { CtkLog.Write(ex); }
            }

            return(0);
        }
Ejemplo n.º 21
0
        void EndConnectCallback(IAsyncResult ar)
        {
            var myea      = new CtkNonStopTcpStateEventArgs();
            var trxBuffer = myea.TrxMessageBuffer;

            try
            {
                //Lock使用在短碼保護, 例如: 保護一個變數的get/set
                //Monitor使用在保護一段代碼

                Monitor.Enter(this);//一定要等到進去
                var state  = (CtkTcpClient)ar.AsyncState;
                var client = state.MyTcpClient;
                client.EndConnect(ar);

                myea.Sender        = state;
                myea.WorkTcpClient = client;
                if (!ar.IsCompleted || client.Client == null || !client.Connected)
                {
                    throw new CtkException("Connection Fail");
                }

                //呼叫他人不應影響自己運作, catch起來
                try { this.OnFirstConnect(myea); }
                catch (Exception ex) { CtkLog.WarnNs(this, ex); }

                if (this.IsAsynAutoRead)
                {
                    var stream = client.GetStream();
                    stream.BeginRead(trxBuffer.Buffer, 0, trxBuffer.Buffer.Length, new AsyncCallback(EndReadCallback), myea);
                }
            }
            //catch (SocketException ex) { }
            catch (Exception ex)
            {
                //失敗就中斷連線, 清除
                this.Disconnect();
                myea.Message   = ex.Message;
                myea.Exception = ex;
                this.OnFailConnect(myea);
                CtkLog.WarnNs(this, ex);
            }
            finally
            {
                this.mreIsConnecting.Set();
                Monitor.Exit(this);
            }
        }
Ejemplo n.º 22
0
        public void RunAsyn()
        {
            CtkLog.RegisterEveryLogWrite((ss, ea) =>
            {
                var now = DateTime.Now;
                var sb  = new StringBuilder();
                sb.AppendFormat("[{0}] ", now.ToString("yyyyMMdd HH:mm:ss"));
                sb.AppendFormat("{0} ", ea.Message);
                sb.AppendFormat("{0}", ea.Exception.StackTrace);
                CtkLog.InfoNs(this, sb.ToString());
            });



            DateTime?prevTime = DateTime.Now;

            this.listener = new CtkNonStopTcpListener("127.0.0.1", 5003);
            listener.NonStopConnectAsyn();
            var rnd = new Random((int)DateTime.Now.Ticks);

            listener.EhFirstConnect += (ss, ee) =>
            {
                var myea = ee as CtkNonStopTcpStateEventArgs;
                var sb   = new StringBuilder();
                sb.Append("evtFirstConnect:\n");
                sb.Append(this.CmdState());
                CtkLog.InfoNs(this, sb.ToString());
            };
            listener.EhDataReceive += (ss, ee) =>
            {
                var myea      = ee as CtkNonStopTcpStateEventArgs;
                var ctkBuffer = myea.TrxMessageBuffer;
                var msg       = Encoding.UTF8.GetString(ctkBuffer.Buffer, ctkBuffer.Offset, ctkBuffer.Length);
                if (!msg.Contains("\n"))
                {
                    return;
                }
                var sb = new StringBuilder();
                sb.Append("cmd -respData -svid 1 -data ");
                sb.Append(rnd.NextDouble());



                sb.AppendLine();

                myea.WriteMsg(sb.ToString());
            };
        }
Ejemplo n.º 23
0
 public static bool DisposeTcpClientTry(TcpClient client)
 {
     try
     {
         DisposeTcpClient(client);
         return(true);
     }
     catch (SocketException) { return(false); }
     catch (ObjectDisposedException) { return(false); }
     catch (InvalidOperationException) { return(false); }
     catch (Exception ex)
     {
         //非預期的Exception, 記錄起來
         CtkLog.Warn(ex);
         return(false);
     }
 }
Ejemplo n.º 24
0
        public void NonStopRunStart()
        {
            this.NonStopRunStop();
            this.runningTask = CtkTask.RunOnce(() =>
            {
                //TODO: 重啟時, 會有執行緒被中止的狀況
                while (!this.disposed)
                {
                    try
                    {
                        this.ConnectTryStart();
                    }
                    catch (Exception ex) { CtkLog.Write(ex); }

                    Thread.Sleep(this.IntervalTimeOfConnectCheck);
                }
            });
        }
Ejemplo n.º 25
0
        public void NonStopRunStart()
        {
            NonStopRunStop();

            this.runningTask = CtkTask.RunOnce((ct) =>
            {
                while (!this.disposed && !ct.IsCancellationRequested)
                {
                    ct.ThrowIfCancellationRequested();
                    try
                    {
                        this.ConnectTry();
                    }
                    catch (Exception ex) { CtkLog.Write(ex); }
                    Thread.Sleep(this.IntervalTimeOfConnectCheck);
                }
            });
        }
Ejemplo n.º 26
0
        public void NonStopConnectAsyn()
        {
            AbortNonStopConnect();

            this.NonStopTask = CtkCancelTask.RunOnce((ct) =>
            {
                while (!this.disposed && !ct.IsCancellationRequested)
                {
                    ct.ThrowIfCancellationRequested();
                    try
                    {
                        this.ConnectIfNo();
                    }
                    catch (Exception ex) { CtkLog.Write(ex); }
                    Thread.Sleep(this.IntervalTimeOfConnectCheck);
                }
            });
        }
        void ClientEndConnectCallback(IAsyncResult ar)
        {
            var myea      = new CtkNonStopTcpStateEventArgs();
            var trxBuffer = myea.TrxMessageBuffer;

            try
            {
                Monitor.Enter(this);//一定要等到進去
                var state  = (CtkNonStopTcpClient)ar.AsyncState;
                var client = state.activeWorkClient;
                client.EndConnect(ar);

                myea.Sender     = state;
                myea.workClient = client;
                if (!ar.IsCompleted || client.Client == null || !client.Connected)
                {
                    myea.Message = "Connection Fail";
                    this.OnFailConnect(myea);
                    return;
                }

                //呼叫他人不應影響自己運作, catch起來
                try { this.OnFirstConnect(myea); }
                catch (Exception ex) { CtkLog.Write(ex); }

                var stream = client.GetStream();
                stream.BeginRead(trxBuffer.Buffer, 0, trxBuffer.Buffer.Length, new AsyncCallback(EndReadCallback), myea);
            }
            catch (SocketException ex)
            {
                myea.Message   = ex.Message;
                myea.Exception = ex;
                this.OnFailConnect(myea);
            }
            catch (Exception ex)
            {
                CtkLog.Write(ex, CtkLoggerEnumLevel.Warn);
            }
            finally
            {
                this.mreIsConnecting.Set();
                Monitor.Exit(this);
            }
        }
Ejemplo n.º 28
0
 public virtual int CfRunOnce()
 {
     try
     {
         this.ProtoConn.ConnectIfNo();//內部會處理重複要求連線
         this.RealExec();
     }
     catch (Exception ex)
     {
         CtkLog.WarnNs(this, ex);
         if (this.Config != null)
         {
             var mymsg = string.Format("Loca={0}, Remote={1}, DeviceUid={2}", this.Config.LocalUri, this.Config.RemoteUri, this.Config.DeviceUid);
             CtkLog.WarnNs(this, mymsg);
         }
         Thread.Sleep(3000);//異常斷線後, 先等3秒再繼續
     }
     return(0);
 }
        public void NonStopConnectAsyn()
        {
            AbortNonStopConnect();

            this.threadNonStopConnect = new Thread(new ThreadStart(delegate()
            {
                while (!disposed)
                {
                    try
                    {
                        this.ConnectIfNo();
                    }
                    catch (Exception ex) { CtkLog.Write(ex); }

                    Thread.Sleep(this.IntervalTimeOfConnectCheck);
                }
            }));
            this.threadNonStopConnect.Start();
        }
        //用途是避免重複要求連線
        public void ConnectIfNo()
        {
            try
            {
                if (!Monitor.TryEnter(this, 1000))
                {
                    return;                               //進不去先離開
                }
                //在Lock後才判斷, 避免判斷無連線後, 另一邊卻連線好了
                if (this.activeWorkClient != null && this.activeWorkClient.Connected)
                {
                    return;                                                                  //連線中直接離開
                }
                if (!mreIsConnecting.WaitOne(10))
                {
                    return;                   //連線中就離開
                }
                this.mreIsConnecting.Reset(); //先卡住, 不讓後面的再次進行連線

                if (this.activeWorkClient != null)
                {
                    var workClient = this.activeWorkClient;
                    try
                    {
                        if (workClient.GetStream() != null)
                        {
                            using (var stm = workClient.GetStream()) stm.Close();
                        }
                    }
                    catch (Exception) { }

                    try { workClient.Close(); }
                    catch (Exception ex) { CtkLog.Write(ex); }

                    this.activeWorkClient = null;
                }
                this.activeWorkClient         = localEP == null ? new TcpClient() : new TcpClient(localEP);
                this.activeWorkClient.NoDelay = true;
                this.activeWorkClient.BeginConnect(this.remoteEP.Address, this.remoteEP.Port, new AsyncCallback(ClientEndConnectCallback), this);
            }
            finally { Monitor.Exit(this); }
        }