C# 使用.NET 4.5的非阻塞TCP服务器

C# 使用.NET 4.5的非阻塞TCP服务器,c#,.net,tcpclient,async-await,tcplistener,C#,.net,Tcpclient,Async Await,Tcplistener,我需要实现一个带有tcp侦听器的Windows服务来无限期地侦听和处理来自tcp端口的数据馈送,我正在寻找使用.NET 4.5异步功能的任何示例 到目前为止,我发现的唯一问题是: class Program { private const int BufferSize = 4096; private static readonly bool ServerRunning = true; static void Main(string[] args) {

我需要实现一个带有tcp侦听器的Windows服务来无限期地侦听和处理来自tcp端口的数据馈送,我正在寻找使用.NET 4.5异步功能的任何示例

到目前为止,我发现的唯一问题是:

class Program
{
    private const int BufferSize = 4096;
    private static readonly bool ServerRunning = true;

    static void Main(string[] args)
    {
        var tcpServer = new TcpListener(IPAddress.Any, 9000);
        try
        {
            tcpServer.Start();
            ListenForClients(tcpServer);
            Console.WriteLine("Press enter to shutdown");
            Console.ReadLine();
        }
        finally
        {
            tcpServer.Stop();
        }
    }

    private static async void ListenForClients(TcpListener tcpServer)
    {
        while (ServerRunning)
        {
            var tcpClient = await tcpServer.AcceptTcpClientAsync();
            Console.WriteLine("Connected");
            ProcessClient(tcpClient);
        }
    }

    private static async void ProcessClient(TcpClient tcpClient)
    {
        while (ServerRunning)
        {
            var stream = tcpClient.GetStream();
            var buffer = new byte[BufferSize];
            var amountRead = await stream.ReadAsync(buffer, 0, BufferSize);
            var message = Encoding.ASCII.GetString(buffer, 0, amountRead);
            Console.WriteLine("Client sent: {0}", message);
        }
    }
}
由于我对这个话题还比较陌生,我想知道:

  • 您对此代码有何改进建议
  • 如何优雅地停止侦听器(现在它抛出
    ObjectDisposedException
  • 是否有更高级的.net tcp侦听器示例

  • 这个问题的大部分都不适合这样做。阅读教程,学习将概念信息从示例转移到不同的用例。唯一有效的子问题是2)。您可以研究WCF异步方法;WCF将允许您通过TCP进行通信。+1@millimoose-对于“您对该代码有何改进建议”的问题,答案是a)它取决于需求,b)可能有很多。阅读更多教程或考虑使用网络库,而不是自己编写所有的网络代码。我是网络图书馆的开发者