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

时间:2013-02-26 17:36:39

标签: c# .net tcpclient async-await tcplistener

我需要使用tcp侦听器实现Windows服务,以无限期地侦听并处理来自tcp端口的数据源,并且我正在寻找使用.NET 4.5异步功能的任何示例。

到目前为止我找到的唯一sample是:

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);
        }
    }
}

因为我对这个话题非常陌生,我想知道:

  1. 您对此代码有何建议?
  2. 如何优雅地停止监听器(现在它会抛出ObjectDisposedException)。
  3. 是否有更高级的.net tcp listener样本?

0 个答案:

没有答案