0

我需要使用 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);
        }
    }
}

由于我对这个主题比较陌生,我想知道:

  1. 您会建议对此代码进行哪些改进?
  2. 如何优雅地停止监听器(现在它会抛出ObjectDisposedException)。
  3. 是否有更高级的 .net tcp 监听器示例?
4

0 回答 0