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 连接将消息发送到服务器,服务器将处理消息并将响应发送回客户端。客户端将显示接收到的响应消息。