2015-10-21 418 views
0

使用tcpClient.BeginConnect會觸發異步回調,即使客戶端沒有任何連接。然後我得到一個關於嘗試.GetStream()的例外。C#BeginConnect回調在未連接時觸發

public void SetupSocket() { 
     try { 
      tcpClient = new TcpClient(); 
      tcpClient.BeginConnect(host, port, ConnectCallback, tcpClient); 
      Console.WriteLine("begin connect"); 
     } 
     catch (Exception e) { 
      return; 
     } 
    } 


    private void ConnectCallback(IAsyncResult result) { 
     if (OnClientEvent != null) 
      OnClientEvent(this, new ClientEventArgs(Action.Connect)); 

     Console.WriteLine("get stream"); 
     stream = tcpClient.GetStream(); 
     Console.WriteLine("got stream"); 

     BeginReadAsync(); 
    } 

輸出get stream然後約嘗試使用GetStream上TcpClient的連接之前異常。

+0

你建議超時(和其他連接例外)的其他行爲?你是否期望即使頻道出現問題,你的回撥也不會被調用? –

回答

1

連接操作完成時調用傳遞給BeginConnect的回調,無論它是否成功連接到端點或失敗。

BeginConnect回調中,您需要用您收到的IAsyncResult對象調用EndConnect,以完成連接操作。在調用EndConnect之前,套接字不可用;之後,如果套接字成功連接,則可以繼續讀寫。

相關問題