在C#中,處理大量并發連接的推薦方法是使用異步編程模型,例如async/await
和Task
Socket
對象來監聽客戶端連接:using System;
using System.Net;
using System.Net.Sockets;
class Program
{
static async Task Main(string[] args)
{
int port = 8080;
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, port);
using var listener = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(localEndPoint);
listener.Listen(100);
Console.WriteLine($"Server listening on port {port}");
while (true)
{
// Accept incoming connections asynchronously
var clientSocket = await listener.AcceptAsync();
HandleClientConnection(clientSocket);
}
}
// ...
}
HandleClientConnection
方法來處理客戶端連接。這里我們使用async/await
和Task
來實現異步處理:// ...
static async void HandleClientConnection(Socket clientSocket)
{
try
{
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = await clientSocket.ReceiveAsync(buffer, SocketFlags.None)) > 0)
{
// Process the received data
string receivedData = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine($"Received: {receivedData}");
// Send a response to the client
byte[] responseData = Encoding.UTF8.GetBytes("Hello from server!");
await clientSocket.SendAsync(responseData, SocketFlags.None);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error handling client connection: {ex.Message}");
}
finally
{
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
}
這種方法利用了C#的異步編程特性,可以有效地處理大量并發連接。當然,根據實際需求,你還可以對代碼進行優化,例如使用連接池、限制并發連接數等。