ASP.NET Core SignalR 完整指南
一、SignalR 简介
SignalR 是一个开源库,用于向 ASP.NET Core 应用程序添加实时 Web 功能。它允许服务器端代码实时将内容推送到连接的客户端,实现双向通信。
核心特性
- 实时双向通信
- 自动传输协商(WebSocket、Server-Sent Events、长轮询)
- 自动重连机制
- 可扩展性支持
- 跨平台支持
二、核心概念
1. Hub(集线器)
Hub 是 SignalR 的核心组件,作为服务器与客户端通信的高级管道。
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
2. 连接管理
- 连接ID:每个客户端连接都有唯一标识符
- 组:可以将多个连接组织到一个命名组中
- 用户:可以将连接与特定用户关联
3. 客户端方法调用模式
- All:发送到所有连接的客户端
- Caller:仅发送到调用方
- Others:发送到除调用方外的所有客户端
- Group:发送到特定组的所有客户端
- User:发送到特定用户的所有连接
三、实际应用场景
1. 实时聊天应用
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
public async Task JoinGroup(string groupName)
{
await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
await Clients.Group(groupName).SendAsync("UserJoined", $"{Context.ConnectionId} joined {groupName}");
}
}
2. 实时仪表板和监控
public class DashboardHub : Hub
{
public async Task UpdateMetrics(Dictionary<string, double> metrics)
{
await Clients.All.SendAsync("MetricsUpdated", metrics);
}
public async Task SendAlert(string severity, string message)
{
await Clients.All.SendAsync("AlertReceived", severity, message);
}
}
3. 协同编辑文档
public class DocumentHub : Hub
{
public async Task UpdateDocument(string documentId, string content, string user)
{
await Clients.Group(documentId).SendAsync("DocumentUpdated", content, user);
}
public async Task JoinDocument(string documentId)
{
await Groups.AddToGroupAsync(Context.ConnectionId, documentId);
}
}
4. 游戏实时状态同步
public class GameHub : Hub
{
public async Task UpdatePlayerPosition(string playerId, double x, double y)
{
await Clients.Others.SendAsync("PlayerMoved", playerId, x, y);
}
public async Task BroadcastGameState(GameState state)
{
await Clients.All.SendAsync("GameStateUpdated", state);
}
}
四、配置和部署
1. 服务器端配置
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR()
.AddStackExchangeRedis("localhost:6379") // 使用Redis进行扩展
.AddJsonProtocol(options => {
options.PayloadSerializerOptions.WriteIndented = true;
});
}
public void Configure(IApplicationBuilder app)
{
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<ChatHub>("/chathub");
});
}
2. 客户端配置(JavaScript)
const connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub")
.withAutomaticReconnect([0, 2000, 5000, null])
.configureLogging(signalR.LogLevel.Information)
.build();
connection.start().catch(err => console.error(err));
connection.on("ReceiveMessage", (user, message) => {
// 处理接收到的消息
});
五、高级特性
1. 消息大小限制配置
services.AddSignalR(options =>
{
options.MaximumReceiveMessageSize = 102400; // 100 KB
});
2. 跨域支持
services.AddCors(options =>
{
options.AddPolicy("SignalRPolicy", builder =>
{
builder.WithOrigins("http://example.com")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
3. 身份验证和授权
public class AuthorizedHub : Hub
{
[Authorize]
public async Task SendMessage(string message)
{
var user = Context.User.Identity.Name;
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
六、性能优化和最佳实践
- 使用 Redis 背板实现扩展
- 实施重试策略
- 使用适当的传输方法
- 实施消息缓冲
- 监控连接状态
- 错误处理
七、故障排除
-
连接问题
- 检查网络连接
- 验证URL配置
- 检查CORS设置
-
性能问题
- 监控消息大小
- 检查并发连接数
- 优化消息频率
八、监控和日志
services.AddSignalR()
.AddHubOptions<ChatHub>(options =>
{
options.EnableDetailedErrors = true;
options.KeepAliveInterval = TimeSpan.FromMinutes(1);
});
总结
SignalR 为实时应用程序开发提供了强大而灵活的解决方案。通过合理使用其提供的特性,可以构建高效、可扩展的实时通信应用。在实际应用中,需要根据具体场景选择适当的实现方式,并注意性能优化和安全性考虑。
作者:阿笨
【官方QQ一群:跟着阿笨一起玩NET(已满)】:422315558
【官方QQ二群:跟着阿笨一起玩C#(已满)】:574187616
【官方QQ三群:跟着阿笨一起玩ASP.NET(已满)】:967920586
【官方QQ四群:Asp.Net Core跨平台技术开发(可加入)】:829227829
【官方QQ五群:.NET Core跨平台开发技术(可加入)】:647639415
【网易云课堂】:https://study.163.com/provider/2544628/index.htm?share=2&shareId=2544628
【51CTO学院】:https://edu.51cto.com/sd/66c64
【微信公众号】:微信搜索:跟着阿笨一起玩NET
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2021-02-04 SQL Server数据库高级进阶之事务实战演练
2021-02-04 C#如何正确运用异步编程技术
2021-02-04 SQL Server数据库高级进阶之锁实战演练
2020-02-04 .NET Core基于SQL Server数据库主从同步实现读写分离实战演练
2013-02-04 将要被社会淘汰的8种人