在ASP.NET中實現WebSocket,你可以使用ASP.NET Core WebSockets。以下是一個簡單的示例,展示了如何在ASP.NET Core應用程序中創建一個WebSocket端點。
dotnet add package Microsoft.AspNetCore.WebSockets
Startup.cs
文件中,將WebSocket中間件添加到Configure
方法中:public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// ... 其他中間件配置
app.UseWebSockets();
// ... 其他中間件配置
}
ChatWebSocketHandler
的類:public class ChatWebSocketHandler
{
private readonly WebSocket _webSocket;
public ChatWebSocketHandler(WebSocket webSocket)
{
_webSocket = webSocket;
}
public async Task OnConnectedAsync()
{
// 當客戶端連接時,發送歡迎消息
var welcomeMessage = "Welcome to the WebSocket server!";
await _webSocket.SendAsync(Encoding.UTF8.GetBytes(welcomeMessage), WebSocketMessageType.Text, true);
}
public async Task OnDisconnectedAsync()
{
// 當客戶端斷開連接時,執行清理操作
}
public async Task OnMessageReceivedAsync(string message)
{
// 處理接收到的消息,并將其廣播給所有連接的客戶端
var broadcastMessage = $"Server received: {message}";
var buffer = Encoding.UTF8.GetBytes(broadcastMessage);
foreach (var client in _webSocket.Server.Connections)
{
if (client.State == WebSocketState.Open)
{
await client.SendAsync(buffer, WebSocketMessageType.Text, true);
}
}
}
}
Startup.cs
文件中,將WebSocket處理程序與一個路由關聯起來。例如,創建一個名為/ws
的路由:public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// ... 其他中間件配置
app.UseWebSockets();
app.UseEndpoints(endpoints =>
{
endpoints.MapWebSocket("/ws", async (context) =>
{
var webSocket = await context.WebSockets.AcceptWebSocketAsync();
var chatHandler = new ChatWebSocketHandler(webSocket);
await chatHandler.OnConnectedAsync();
byte[] buffer = new byte[1024 * 4];
WebSocketReceiveResult result;
do
{
result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
var message = Encoding.UTF8.GetString(buffer, 0, result.Count);
await chatHandler.OnMessageReceivedAsync(message);
}
while (!result.CloseStatus.HasValue);
await chatHandler.OnDisconnectedAsync();
});
// ... 其他路由配置
});
}
現在,你已經創建了一個簡單的WebSocket服務器,客戶端可以通過連接到/ws
端點來與服務器進行通信。你可以根據需要擴展ChatWebSocketHandler
類以處理更復雜的邏輯,例如連接管理、消息格式化和廣播等。