在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#的异步编程特性,可以有效地处理大量并发连接。当然,根据实际需求,你还可以对代码进行优化,例如使用连接池、限制并发连接数等。