我一直在做一個服務器。我在async
方法中使用TcpListener.AcceptTcpClientAsync(),但我不知道如何真正使它工作。我現在的代碼是:接受TCP客戶端異步
private static async void StartServer()
{
Console.WriteLine("S: Server started on port {0}", WebVars.ServerPort);
var listener = new TcpListener(WebVars.LocalIp, WebVars.ServerPort);
listener.Start();
var client = await listener.AcceptTcpClientAsync();
}
如何處理客戶端?我是否繼續編寫代碼,它會自動創建同一方法的新線程,還是需要執行一些可以幫我實現的魔術方法?
編輯:當前代碼:
private static Task HandleClientAsync(TcpClient client)
{
var stream = client.GetStream();
// do stuff
}
/// <summary>
/// Method to be used on seperate thread.
/// </summary>
private static async void RunServerAsync()
{
while (true)
{
Console.WriteLine("S: Server started on port {0}", WebVars.ServerPort);
var listener = new TcpListener(WebVars.LocalIp, WebVars.ServerPort);
listener.Start();
var client = await listener.AcceptTcpClientAsync();
await HandleClientAsync(client);
}
}
請不要包含關於問題標題中使用的語言的信息,除非在沒有它的情況下沒有意義。標籤用於此目的。 –
這是相關的:http://stackoverflow.com/questions/21013751/what-is-the-async-await-equivalent-of-a-threadpool-server – Noseratio