微软教程:ASP.NET Core SignalR 入门
项目结构

运行效果

前端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SignalR Demo</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/5.0.8/signalr.min.js"></script>
</head>
<body>
<h1>SignalR即时通信演示</h1>
<div>
<input type="text" id="userInput" placeholder="用户名(可选)" />
<input type="text" id="messageInput" placeholder="请输入消息" />
<button id="sendButton">发送</button>
</div>
<ul id="messages"></ul>
<script>
$(document).ready(function () {
var connection = new signalR.HubConnectionBuilder()
.withUrl("/chatHub")
.build();
connection.start().catch(function (err) {
return console.error(err.toString());
});
connection.on("ReceiveMessage", function (user, message) {
var msg = "<strong>" + user + ":</strong> " + message;
$("#messages").append("<li>" + msg + "</li>");
});
$("#sendButton").click(function () {
var user = $("#userInput").val() || "匿名用户";
var message = $("#messageInput").val();
connection.invoke("SendMessage", user, message).catch(function (err) {
return console.error(err.toString());
});
$("#messageInput").val("");
});
});
</script>
</body>
</html>
后台
using Microsoft.AspNetCore.SignalR;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSignalR();
var app = builder.Build();
app.UseStaticFiles();
app.UseRouting();
app.MapHub<ChatHub>("/chatHub");
app.Run();
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
Comments