文章目录
- 前提
- 环境
- nuget 包
- 开始改造
- Program 的main函数
- 完整代码
- WarningBroadcastHub
- 完整代码
- 结束语
前提
本文不介绍关于SignalR的原理内容,比如如何实现的长连接,如何实现双工通信,如何实现向下兼容的通信等等
本文仅仅记录如何实现一个服务端
环境
- IDE :visual Studio2022
- 环境:.net6 webApi程序
- 语言:C#10
nuget 包
没有引入其他包,因为是WebApi项目,所以默认的asp.net的包都引入了。
开始改造
Program 的main函数
//增加SignalR的服务 builder.Services.AddSignalR();
//指定Hub的路径和处理类app.MapHub("/sr/warning_broadcast");
完整代码
using Demo_WarningMonitor.Api.Services;using Demo_WarningMonitor.Api.SignalRHubs;using Demo_WarningMonitor.Api.Workers;using Microsoft.AspNetCore.SignalR;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Hosting.WindowsServices;namespace Demo_WarningMonitor.Api{public class Program{public static void Main(string[] args){var builder = WebApplication.CreateBuilder(args);IConfiguration configuration = builder.Configuration;var options = new WebApplicationOptions{Args = args,ContentRootPath = WindowsServiceHelpers.IsWindowsService()? AppContext.BaseDirectory : default};// Add services to the container. builder.Services.AddControllers();builder.Services.AddSignalR();// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbucklebuilder.Services.AddEndpointsApiExplorer();builder.Services.AddSwaggerGen(); var app = builder.Build();// Configure the HTTP request pipeline.//if (app.Environment.IsDevelopment())//{app.UseSwagger();app.UseSwaggerUI();//}app.UseStaticFiles();app.UseHttpsRedirection();app.UseAuthorization();app.MapControllers();#region SignalRapp.MapHub("/sr/warning_broadcast"); #endregion app.Run();}}}
WarningBroadcastHub
一个自己定义的Hub处理类,继承自Hub
引入命名空间
using Microsoft.AspNetCore.SignalR;
完整代码
using Microsoft.AspNetCore.SignalR;namespace Demo_WarningMonitor.Api.SignalRHubs{/// /// 报警广播/// public class WarningBroadcastHub : Hub{ private ILogger logger; public WarningBroadcastHub(ILogger logger, IConfiguration configuration){this.logger = logger; }public async Task SendMessage(string user, string message){try{await Clients.All.SendAsync("ReceiveMessage", user, message);}catch (Exception ex){logger.LogError(ex,"发送消息出现异常");}}}}
结束语
到此为止一个服务端就做完了,运行起来也是看不到任何效果的。那么如何才能看到效果呢,请看下一篇文章
SignalR javascript 客户端