我需要使用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);
}
}
}
因为我对这个话题非常陌生,我想知道:
ObjectDisposedException
)。