在C#中,處理并發連接通常涉及到使用異步編程模型。BeginReceive
方法是異步接收數據的關鍵,它可以讓你在等待數據到達時執行其他任務。以下是一個簡單的示例,展示了如何使用 BeginReceive
處理并發連接:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
class ConcurrentServer
{
private const int Port = 8080;
private const int BufferSize = 1024;
private TcpListener _listener;
public ConcurrentServer()
{
_listener = new TcpListener(IPAddress.Any, Port);
}
public void Start()
{
_listener.Start();
Console.WriteLine("Server started on port " + Port);
Task.Run(() => AcceptClients());
}
private async Task AcceptClients()
{
while (true)
{
var client = await _listener.AcceptTcpClientAsync();
Console.WriteLine("Client connected: " + client.Client.RemoteEndPoint);
// Handle the client connection in a separate task
_ = HandleClientAsync(client);
}
}
private async Task HandleClientAsync(TcpClient client)
{
var stream = client.GetStream();
byte[] buffer = new byte[BufferSize];
while (true)
{
// Asynchronously receive data from the client
int bytesRead = await stream.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None);
if (bytesRead == 0)
{
// The client has disconnected
break;
}
// Process the received data
string data = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received from client: " + data);
// Echo the data back to the client
byte[] response = Encoding.UTF8.GetBytes("Echo: " + data);
await stream.WriteAsync(response, 0, response.Length);
}
client.Close();
Console.WriteLine("Client disconnected: " + client.Client.RemoteEndPoint);
}
public static void Main(string[] args)
{
var server = new ConcurrentServer();
server.Start();
}
}
在這個示例中,我們創建了一個簡單的TCP服務器,它使用 BeginReceive
異步接收客戶端發送的數據。每當有新的客戶端連接時,服務器會創建一個新的任務來處理該客戶端的連接。這樣,服務器就可以同時處理多個并發連接。