2014-03-05 56 views
4

我已經編寫了以下Tcp Server應用程序。問題是它不是並行執行單個客戶端。即如果一個客戶端連接,服務器不接受到其他客戶端的連接。請大家幫我修復代碼:具有await&async的C#5.0異步TCP/IP服務器

void Run() 
{ 
    tcpListener.Start();   

    while (true) 
    { 
     Console.WriteLine("Waiting for a connection..."); 

     try 
     { 
      var client = await tcpListener.AcceptTcpClientAsync(); 
      await Accept(client); 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex.Message); 
     } 
    } 
} 

private async Task Accept(TcpClient client) 
{ 
    //get client information 
    string clientEndPoint = GetClientIPAddress(client);    
    Console.WriteLine("Client connected at " + clientEndPoint); 
    log.Info("Client connected at " + clientEndPoint); 

    await Task.Yield(); 

    try 
    {    
     using (client) 
      using (NetworkStream stream = client.GetStream()) 
      { 
       byte[] dataReceived = new byte [50];     
       while (await stream.ReadAsync(dataReceived, 0, dataReceived.Length) != 0) //read input stream     
       {      
        //process data here       
        await ProcessData(dataReceived);      
       }     
      } 
    } //end try 
    catch (Exception ex) 
    { 
     Console.WriteLine(ex.Message);     
     if (client.Connected) 
      client.Close(); 
    } 
} //end Accept(TcpClient client) 
+0

您是否嘗試多次連接到相同的端口? – maf748

回答

3

問題是這樣的:

await Accept(client); 

你等待的Accept的結果,所以你無法接受新的連接(因爲你不執行AcceptTcpClientAsync,而Accept是「正在進行中」)。

下面是如何正確完成的示例:https://stackoverflow.com/a/21018042/1768303

+0

您應該將其更改爲'async void Accept(client){...}',並且只需在Run方法中不帶'await'關鍵字的情況下調用它即可。 – Laith

+0

@Laith,我不是'async void'遺忘和忘記方法的忠實粉絲。我更願意跟蹤掛起的任務,如鏈接[答案](http://stackoverflow.com/a/21018042/1768303)中所做的那樣。 – Noseratio

+0

你是對的。如果你想跟蹤所有正在運行的任務,你會想保持對它們的引用。你的方法更好:) – Laith