C# 高并发tcp服务器
时间: 2024-10-28 12:12:54 浏览: 9
C#高并发SOCKET服务器和客户端完整工程实例源码.zip
5星 · 资源好评率100%
在C#中创建高并发TCP服务器,通常需要利用异步I/O模型(如`Asynchronous Operations`),尤其是`TcpListener`和`Socket`类。下面是一个简单的异步TCP服务器示例:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
class Program
{
private TcpListener listener;
public async Task StartServer(int port)
{
listener = new TcpListener(IPAddress.Any, port);
listener.Start();
Console.WriteLine($"Server started on {listener.LocalEndpoint}.");
while (true)
{
// 等待连接
var client = await listener.AcceptTcpClientAsync();
// 创建一个新的线程处理每个连接
var clientHandler = new ClientHandler(client);
ThreadPool.QueueUserWorkItem(clientHandler.ProcessConnection);
}
}
class ClientHandler : IAsyncDisposable
{
private readonly TcpClient client;
public ClientHandler(TcpClient client)
{
this.client = client;
}
public ValueTask DisposeAsync()
{
client.Close();
return default;
}
public void ProcessConnection(object state)
{
try
{
using (var stream = client.GetStream())
{
// 实现收发数据的异步操作
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
Console.WriteLine("Received data from client: " + Encoding.ASCII.GetString(buffer, 0, bytesRead));
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error handling client: {ex.Message}");
}
}
}
static void Main(string[] args)
{
var serverPort = 8080;
var serverTask = new Program().StartServer(serverPort);
serverTask.Wait(); // 如果你需要让程序等待服务器关闭
}
}
```
这个示例中,服务器持续监听指定端口的连接,并在新的线程上处理每个客户端。`ClientHandler`类实现了异步接收和处理客户端数据。`IAsyncDisposable`接口使得在结束连接时可以异步关闭套接字,提高资源管理效率。
阅读全文