您好,登錄后才能下訂單哦!
在C#中,您可以使用ASP.NET Core的WebSocket API來處理WebSocket消息
首先,確保已安裝ASP.NET Core。如果尚未安裝,請訪問 https://dotnet.microsoft.com/download 并按照說明進行操作。
創建一個新的ASP.NET Core Web應用程序項目。在命令提示符或終端中,運行以下命令:
dotnet new webapp -o WebSocketExample
cd WebSocketExample
Startup.cs
文件,然后在Configure
方法中添加以下代碼以啟用WebSocket中間件:app.UseWebSockets();
Startup.cs
文件中,導入以下命名空間:using System.Net.WebSockets;
using System.Threading.Tasks;
WebSocketController.cs
),并添加以下代碼:using System;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
[Route("api/websocket")]
public class WebSocketController : ControllerBase
{
[HttpGet]
public async Task Get()
{
if (HttpContext.WebSockets.IsWebSocketRequest)
{
using var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
await ProcessWebSocket(webSocket);
}
else
{
HttpContext.Response.StatusCode = 400;
}
}
private async Task ProcessWebSocket(WebSocket webSocket)
{
var buffer = new byte[1024 * 4];
var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
while (!result.CloseStatus.HasValue)
{
// Process the received message
var message = System.Text.Encoding.UTF8.GetString(buffer, 0, result.Count);
Console.WriteLine($"Received message: {message}");
// Send a response to the client
var response = "Message received";
var responseBytes = System.Text.Encoding.UTF8.GetBytes(response);
await webSocket.SendAsync(new ArraySegment<byte>(responseBytes), WebSocketMessageType.Text, true, CancellationToken.None);
// Wait for the next message
result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
}
await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
}
}
/api/websocket
端點。您可以使用JavaScript的WebSocket
對象來實現客戶端連接。以下是一個簡單的HTML和JavaScript示例:<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket Example</title>
</head>
<body>
<script>
const socket = new WebSocket('ws://localhost:5000/api/websocket');
socket.onopen = (event) => {
console.log('WebSocket connection opened:', event);
socket.send('Hello, server!');
};
socket.onmessage = (event) => {
console.log('Received message from server:', event.data);
};
socket.onclose = (event) => {
console.log('WebSocket connection closed:', event);
};
socket.onerror = (event) => {
console.error('WebSocket error:', event);
};
</script>
</body>
</html>
將此HTML代碼保存為index.html
文件,并在瀏覽器中打開它。查看瀏覽器的開發者工具中的控制臺,您應該會看到與服務器的WebSocket連接以及發送和接收的消息。
這就是如何在C#中使用ASP.NET Core處理WebSocket消息。您可以根據需要修改ProcessWebSocket
方法以處理不同類型的消息和響應。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。