/// <summary> /// Asynchronization Callback /// </summary> /// <param name="ar"></param> private void AcceptCallback(IAsyncResult ar) { ClientRequestHandler client = null; bool setFlag = false; try { //連線等待1秒 if (ar.AsyncWaitHandle.WaitOne(1000)) { if (ar.IsCompleted) { client = ((ClientRequestHandler)ar.AsyncState); client.ClientSocket = client.MainSocket.EndAccept(ar); setFlag = this.AcceptConnectEvent.Set(); //開始執行工作流程 client.DoCommunicate(); } } else { //目前測試不出這種狀況,或許需要拉到mainSocket.BeginAccept下跑才有用 //Console.WriteLine("[掛了沒連上]"); log.Error(m => m("[AcceptCallback]建立連線逾時")); client = ((ClientRequestHandler)ar.AsyncState); client.ClientSocket = client.MainSocket.EndAccept(ar); client.CancelAsync(); } } catch (SocketException sckEx) { //Console.WriteLine("[AcceptCallback]Socket Error:" + sckEx.Message + Environment.NewLine + sckEx.StackTrace); log.Error(m => m("[AcceptCallback]Socket Error:" + sckEx.Message + Environment.NewLine + sckEx.StackTrace)); } catch (Exception ex) { //Console.WriteLine("[AcceptCallback]Callback Error:" + ex.Message + Environment.NewLine + ex.StackTrace); log.Error(m => m("[AcceptCallback]Callback Error:" + ex.Message + Environment.NewLine + ex.StackTrace)); } finally { //this.AcceptConnectEvent.Set(); if (!setFlag) { try { this.AcceptConnectEvent.Set(); } catch (ObjectDisposedException objDisposeEx) { //Console.WriteLine(" AcceptConnectEvent Error: {0}", objDisposeEx.Message); log.Error(m => m(" AcceptConnectEvent Error: {0}", objDisposeEx.Message)); } } } }
public void Handle(ClientRequestHandler handler) { //Console.WriteLine("Exit State ..."); log.Debug(m => m("Exit State ...")); handler.CancelAsync(); }