在C#中實現WebSocket接口后端的話,可以使用ASP.NET Core中的WebSocket類庫來實現。以下是一個簡單的示例代碼:
using System;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
public class WebSocketHandler
{
private readonly WebSocket _socket;
public WebSocketHandler(WebSocket socket)
{
_socket = socket;
}
public async Task HandleWebSocketRequest(HttpContext context)
{
var buffer = new byte[1024];
WebSocketReceiveResult result = await _socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
while (!result.CloseStatus.HasValue)
{
// 處理接收到的數據
string message = System.Text.Encoding.UTF8.GetString(buffer);
Console.WriteLine($"Received message: {message}");
// 發送響應數據
string responseMessage = "Hello from server!";
byte[] responseBuffer = System.Text.Encoding.UTF8.GetBytes(responseMessage);
await _socket.SendAsync(new ArraySegment<byte>(responseBuffer), WebSocketMessageType.Text, true, CancellationToken.None);
result = await _socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
}
await _socket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
}
}
在你的ASP.NET Core應用程序中,可以通過一個中間件來處理WebSocket請求:
app.UseWebSockets();
app.Use(async (context, next) =>
{
if (context.WebSockets.IsWebSocketRequest)
{
WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
var handler = new WebSocketHandler(webSocket);
await handler.HandleWebSocketRequest(context);
}
else
{
await next();
}
});
在這個示例中,我們創建了一個WebSocketHandler
類來處理WebSocket連接,并在中間件中進行處理。當接收到WebSocket請求時,會創建一個新的WebSocketHandler
實例,并調用HandleWebSocketRequest
方法來處理WebSocket消息。
希望這個簡單示例可以幫助你在C#中實現WebSocket接口后端。