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); } }
void EndConnectCallback(IAsyncResult ar) { var stateea = new CtkNonStopTcpStateEventArgs(); var ctkBuffer = stateea.TrxMessageBuffer; try { // End the operation and display the received data on // the console. var state = (CtkNonStopTcpListener)ar.AsyncState; stateea.Sender = state; var tcpClient = state.m_tcpListener.EndAcceptTcpClient(ar); stateea.workClient = tcpClient; this.m_tcpListener.BeginAcceptTcpClient(new AsyncCallback(EndConnectCallback), this); if (tcpClient.Client == null || !tcpClient.Connected) { throw new CtkException("連線失敗"); } this.TcpClientList.Enqueue(tcpClient); //呼叫他人不應影響自己運作, catch起來 try { this.OnFirstConnect(stateea); } catch (Exception ex) { CtkLog.Write(ex); } NetworkStream stream = tcpClient.GetStream(); stream.BeginRead(ctkBuffer.Buffer, 0, ctkBuffer.Buffer.Length, new AsyncCallback(EndReadCallback), stateea); } catch (Exception ex) { stateea.Message = ex.Message; stateea.Exception = ex; this.OnFailConnect(stateea); } finally { } }