我已經編寫了以下Tcp Server應用程序。問題是它不是並行執行單個客戶端。即如果一個客戶端連接,服務器不接受到其他客戶端的連接。請大家幫我修復代碼:具有await&async的C#5.0異步TCP/IP服務器
void Run()
{
tcpListener.Start();
while (true)
{
Console.WriteLine("Waiting for a connection...");
try
{
var client = await tcpListener.AcceptTcpClientAsync();
await Accept(client);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
private async Task Accept(TcpClient client)
{
//get client information
string clientEndPoint = GetClientIPAddress(client);
Console.WriteLine("Client connected at " + clientEndPoint);
log.Info("Client connected at " + clientEndPoint);
await Task.Yield();
try
{
using (client)
using (NetworkStream stream = client.GetStream())
{
byte[] dataReceived = new byte [50];
while (await stream.ReadAsync(dataReceived, 0, dataReceived.Length) != 0) //read input stream
{
//process data here
await ProcessData(dataReceived);
}
}
} //end try
catch (Exception ex)
{
Console.WriteLine(ex.Message);
if (client.Connected)
client.Close();
}
} //end Accept(TcpClient client)
您是否嘗試多次連接到相同的端口? – maf748