2015-02-24 71 views

回答

1

同步和異步連接/發送/接收方法可以混合使用。但是你必須注意不要同時進行2個呼叫,例如Connecting with BeginnConnect,然後直接嘗試使用Receive。

您可以使用IAsyncResult來確定異步調用是否已完成。

這個例子工程沒有問題,使用在相同PC上的TCP回聲服務器:

Socket myAsyncConnectSocket = new Socket(SocketType.Stream, ProtocolType.Tcp); 
myAsyncConnectSocket.ReceiveTimeout = 10; 
myAsyncConnectSocket.SendTimeout = 10; 
int connectTimeout = 10; 
var asyncResult = myAsyncConnectSocket.BeginConnect(
    new IPEndPoint(IPAddress.Loopback, 57005), null, null); 
bool timeOut = true; 
if (asyncResult.AsyncWaitHandle.WaitOne(connectTimeout)) 
{ 
    timeOut = false; 
    Console.WriteLine("Async Connected"); 
    try 
    { 
     myAsyncConnectSocket.Send(Encoding.ASCII.GetBytes("Test 1 2 3")); 
     Console.WriteLine("Sent"); 
     byte[] buffer = new byte[128]; 
     myAsyncConnectSocket.Receive(buffer); 
     Console.WriteLine("Received: {0}", Encoding.ASCII.GetString(buffer)); 
    } 
    catch (SocketException se) 
    { 
     if (se.SocketErrorCode == SocketError.TimedOut) timeOut = true; 
     else throw; 
    } 
} 
Console.WriteLine("Timeout occured: {0}", timeOut); 

以一個特殊的外觀爲asyncResult.AsyncWaitHandle.WaitOne(),因爲它阻止當前線程,直到異步連接完成後,你必須要管理如果你想在不同的線程上連接/發送/接收,那麼這個連接就是你自己的狀態。

相關問題