ASP.NET Socket 数据传输主要涉及到创建一个套接字服务器,监听客户端连接,接收和发送数据。以下是一个简单的示例,展示了如何使用 ASP.NET Core 创建一个 Socket 服务器来传输数据:
dotnet new console -o AspNetCoreSocketServer
cd AspNetCoreSocketServer
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
SocketServer
的新类,该类将包含服务器的主要逻辑:public class SocketServer
{
private const int Port = 5000;
public static async Task Main(string[] args)
{
var server = new SocketServer();
await server.Start();
}
public async Task Start()
{
var listener = new TcpListener(IPAddress.Any, Port);
listener.Start();
Console.WriteLine($"Server started on port {Port}");
while (true)
{
var client = await listener.AcceptTcpClientAsync();
Console.WriteLine($"Client connected: {client.Client.RemoteEndPoint}");
var task = HandleClientAsync(client);
Task.Run(task);
}
}
private async Task HandleClientAsync(TcpClient client)
{
var stream = client.GetStream();
byte[] buffer = new byte[1024];
while (true)
{
int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
if (bytesRead == 0) break;
string receivedData = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine($"Received data: {receivedData}");
string response = "Message received";
byte[] responseBytes = Encoding.UTF8.GetBytes(response);
await stream.WriteAsync(responseBytes, 0, responseBytes.Length);
}
client.Close();
Console.WriteLine($"Client disconnected: {client.Client.RemoteEndPoint}");
}
}
Program.cs
中调用 SocketServer
类的 Main
方法来启动服务器:public static async Task Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// ... 其他配置
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
await SocketServer.Main(args);
}
现在,当客户端连接到服务器时,服务器将接收客户端发送的数据,并在控制台中显示接收到的消息。同时,服务器将发送一条确认消息给客户端。
要测试此服务器,可以创建一个简单的 ASP.NET Core 控制台应用程序,使用 TcpClient
类连接到服务器并发送/接收数据。