在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 = https://www.yisu.com/ask/Encoding.UTF8.GetString(buffer, 0, bytesRead);"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
异步接收客户端发送的数据。每当有新的客户端连接时,服务器会创建一个新的任务来处理该客户端的连接。这样,服务器就可以同时处理多个并发连接。