ASP.NET Core WebSocket 是一種在 ASP.NET Core 應用程序中實現實時雙向通信的技術。以下是使用 ASP.NET Core WebSocket 的流程:
Startup.cs
文件中的 Configure
方法中添加以下代碼來實現:public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapWebSocket("/ws");
});
}
IDisposable
接口來實現:public class MyWebSocketHandler : IDisposable
{
private readonly WebSocket _webSocket;
private readonly Task _listenTask;
public MyWebSocketHandler(WebSocket webSocket)
{
_webSocket = webSocket;
_listenTask = ListenAsync();
}
private async Task ListenAsync()
{
while (! _webSocket.CloseStatus.HasValue)
{
var result = await _webSocket.ReceiveAsync();
if (result.CloseStatus.HasValue)
{
break;
}
// 處理接收到的消息
var message = Encoding.UTF8.GetString(result.Buffer);
Console.WriteLine($"Received message: {message}");
// 發送響應消息
var response = Encoding.UTF8.GetBytes($"Echo: {message}");
await _webSocket.SendAsync(new ArraySegment<byte>(response), result.MessageType, result.EndOfMessage);
}
}
public void Dispose()
{
_webSocket.Dispose();
}
}
HomeController.cs
文件中,可以添加一個處理 WebSocket 連接的方法:[HttpGet]
public async Task<IActionResult> Index(string id)
{
if (id == "ws")
{
var webSocket = new WebSocketOptions
{
// 設置 WebSocket 選項,如子協議等
};
using (var handler = new MyWebSocketHandler(HttpContext.WebSockets.AcceptWebSocket(webSocket)))
{
// 等待 WebSocket 連接關閉
await handler.ListenTask;
}
}
return View();
}
WebSocket
API 來實現:<!DOCTYPE html>
<html>
<head>
<title>WebSocket Example</title>
</head>
<body>
<h1>WebSocket Example</h1>
<input type="text" id="messageInput" placeholder="Type a message">
<button id="sendButton">Send</button>
<ul id="messages"></ul>
<script>
const webSocket = new WebSocket('ws://' + window.location.host + '/ws');
webSocket.addEventListener('open', (event) => {
console.log('WebSocket connection opened:', event);
});
webSocket.addEventListener('message', (event) => {
const messagesList = document.getElementById('messages');
const messageItem = document.createElement('li');
messageItem.textContent = event.data;
messagesList.appendChild(messageItem);
});
document.getElementById('sendButton').addEventListener('click', () => {
const input = document.getElementById('messageInput');
webSocket.send(input.value);
input.value = '';
});
</script>
</body>
</html>
現在,當用戶訪問前端頁面并輸入一條消息后,瀏覽器將通過 WebSocket 連接將消息發送到服務器,服務器將處理消息并將響應發送回客戶端。客戶端將顯示接收到的響應消息。