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

I wrote the following Tcp Server applictaion application. The problem is that it does not execute individual clients in parallel. That is, if one client is connected, the server does not 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)
+4
source share
1 answer

The problem is this:

await Accept(client);

The result is expected Accept, so you can not accept new connections (since you are not performing AcceptTcpClientAsync, but Accept- "in flight").

Here is an example of how this can be done correctly: fooobar.com/questions/292366 / ... .

+4
source

Source: https://habr.com/ru/post/1530330/


All Articles