简体   繁体   English

具有等待和异步的C#5.0异步TCP / IP服务器

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

I have written following Tcp Server applictaion. 我写了以下Tcp Server应用程序。 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)

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"). 你等待的结果Accept ,所以你无法接受新的连接(如你不执行AcceptTcpClientAsyncAccept的“飞行”)。

Here is an example of how it can be done properly: https://stackoverflow.com/a/21018042/1768303 . 以下是如何正确完成的示例: https//stackoverflow.com/a/21018042/1768303

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM