前提
本文不介绍关于SignalR的原理内容,比如如何实现的长连接,如何实现双工通信,如何实现向下兼容的通信等等
本文仅仅记录如何实现一个服务端
环境
- IDE :visual Studio2022
- 环境:.net6 webApi程序
- 语言:C#10
nuget 包
没有引入其他包,因为是WebApi项目,所以默认的asp.net的包都引入了。
开始改造
Program 的main函数
//增加SignalR的服务
builder.Services.AddSignalR();
//指定Hub的路径和处理类
app.MapHub<WarningBroadcastHub>("/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/swashbuckle
builder.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 SignalR
app.MapHub<WarningBroadcastHub>("/sr/warning_broadcast");
#endregion
app.Run();
}
}
}
WarningBroadcastHub
一个自己定义的Hub处理类,继承自Hub
引入命名空间
using Microsoft.AspNetCore.SignalR;
完整代码
using Microsoft.AspNetCore.SignalR;
namespace Demo_WarningMonitor.Api.SignalRHubs
{
/// <summary>
/// 报警广播
/// </summary>
public class WarningBroadcastHub : Hub
{
private ILogger<WarningBroadcastHub> logger;
public WarningBroadcastHub(ILogger<WarningBroadcastHub> 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,"发送消息出现异常");
}
}
}
}
结束语
到此为止一个服务端就做完了,运行起来也是看不到任何效果的。那么如何才能看到效果呢,请看下一篇文章文章来源:https://www.toymoban.com/news/detail-493149.html
SignalR javascript 客户端文章来源地址https://www.toymoban.com/news/detail-493149.html
到了这里,关于NetCore_signalR服务端的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!