写在前面
ASP.NET SignalR 是一个开源代码库,简化了Web实时通讯方案,可以实时地通过服务端将信息同步推送到各个客户端,可应用于
需要从服务器进行高频更新的应用:包括游戏、社交网络、投票、拍卖、地图和GPS应用;
仪表盘和监视应用:包括公司仪表板、即时销售更新或旅行报警;
协同类应用:包括白板应用和团队会议软件;
通知应用:社交网络、电子邮件、聊天、游戏、旅行报警和其他应用都需要使用的通知。
通常情况下 SignalR 优先使用 WebSocket 进行传输,在浏览器不支持WebSocket的情况下才会采用旧的Http传输方式。
本文主要参考官方示例:
ASP.NET Core SignalR 入门 | Microsoft Learn
项目结构 如下:
需要添加客户端库
代码实现
服务端实现
using SignalRChat.Hubs;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddSignalR();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.MapHub<ChatHub>("/chatHub");
app.Run();
using Microsoft.AspNetCore.SignalR;
namespace SignalRChat.Hubs
{
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
}
客户端实现
"use strict";
var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
//Disable the send button until connection is established.
document.getElementById("sendButton").disabled = true;
connection.on("ReceiveMessage", function (user, message) {
var li = document.createElement("li");
document.getElementById("messagesList").appendChild(li);
// We can assign user-supplied strings to an element's textContent because it
// is not interpreted as markup. If you're assigning in any other way, you
// should be aware of possible script injection concerns.
li.textContent = `${user} says ${message}`;
});
connection.start().then(function () {
document.getElementById("sendButton").disabled = false;
}).catch(function (err) {
return console.error(err.toString());
});
document.getElementById("sendButton").addEventListener("click", function (event) {
var user = document.getElementById("userInput").value;
var message = document.getElementById("messageInput").value;
connection.invoke("SendMessage", user, message).catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});