AM0
AM0

Reputation: 175

C#5.0 asynchronous TCP/IP server with await & async

I have written following Tcp Server applictaion. The problem is it is not executing individual clients in parallel. That is if one client is connected, the server doesn't accept connections to other clients. Please help me fix the code:

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)

Upvotes: 4

Views: 12865

Answers (1)

noseratio
noseratio

Reputation: 61686

The problem is this:

await Accept(client);

You're awaiting the result of Accept, so you're unable to accept new connections (as you're not executing AcceptTcpClientAsync while Accept is "in-flight").

Here is an example of how it can be done properly: https://stackoverflow.com/a/21018042/1768303.

Upvotes: 4

Related Questions