,net 5.0 使用Kestrel创建tcp服务器
时间: 2024-03-20 18:40:35 浏览: 133
可以使用Kestrel和System.Net.Sockets命名空间来创建TCP服务器。下面是一个简单的示例:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace TcpServerExample
{
class Program
{
static async Task Main(string[] args)
{
var host = new HostBuilder()
.ConfigureWebHost(webHost =>
{
webHost.UseKestrel(options =>
{
options.Listen(IPAddress.Any, 8080, listenOptions =>
{
listenOptions.UseConnectionHandler<CustomTcpServer>();
});
});
})
.Build();
await host.RunAsync();
}
}
public class CustomTcpServer : ConnectionHandler
{
public override async Task OnConnectedAsync(ConnectionContext connection)
{
var remoteEndPoint = connection.RemoteEndPoint;
Console.WriteLine($"Client connected: {remoteEndPoint}");
while (true)
{
var buffer = new byte[1024];
var result = await connection.Transport.ReceiveAsync(new Memory<byte>(buffer));
if (result.ConnectionClosed || result.BytesTransferred == 0)
{
Console.WriteLine($"Client disconnected: {remoteEndPoint}");
break;
}
var message = System.Text.Encoding.UTF8.GetString(buffer, 0, result.BytesTransferred);
Console.WriteLine($"Received message from {remoteEndPoint}: {message}");
var responseMessage = $"Server received message: {message}";
var responseBytes = System.Text.Encoding.UTF8.GetBytes(responseMessage);
await connection.Transport.SendAsync(new ReadOnlyMemory<byte>(responseBytes));
}
}
}
}
```
在上面的示例中,我们使用了`UseConnectionHandler`方法来指定自定义的TCP服务器处理程序。`CustomTcpServer`类继承自`ConnectionHandler`,并实现了`OnConnectedAsync`方法,这个方法在客户端连接成功时会被调用。在`OnConnectedAsync`方法中,我们使用`Transport`属性来发送和接收数据。
阅读全文