近期项目需要用到signalr,弄了个入门的简单前后端分离demo
文章介绍一下怎么用signalr实现一个简单的聊天室及后台推送
文章底部有资源地址及gitee地址,感兴趣的可以下载查看,文章能帮助到大家的话请给个赞
新建一个.net 5 的asp .net core webapi项目
1.右键管理nuget程序包 安装Microsoft.AspNetCore.Signalr
2.在新建项目下添加hubs文件夹>文件夹新建 ChatHub.cs文件
using Microsoft.AspNetCore.SignalR;
using System;
using System.Threading.Tasks;
namespace SignalrWebApi.Hubs
{
public class ChatHub : Hub
{
///
/// 接收前端消息,并发送给连接的全部用户
///
///
///
///
public async Task HandMessage(string user, string message)
{
//TO DO 可以加缓存,存储用户信息和对应的连接Id
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
///
/// 连接成功
///
///
public override async Task OnConnectedAsync()
{
await Clients.All.SendAsync("ConnectMessage", Context.ConnectionId);
}
///
/// 退出连接
///
///
public override async Task OnDisconnectedAsync(Exception? exception)
{
//TO DO 可以从缓存,返回对应掉线用户,同时清除改用户缓存
await Clients.All.SendAsync("ConnectMessage", Context.ConnectionId, exception?.Message);
}
}
}
3.Startup.cs 配置
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using SignalrDemoApi.Hubs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SignalrDemoApi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSignalR(); //添加SignalR
//创建项目时勾选openapi支持会自动创建Swagger相关内容
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "SignalrDemoApi", Version = "v1" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "SignalrDemoApi v1"));
}
app.UseRouting();
app.UseCors(option => option.WithOrigins("http://localhost:53649").AllowCredentials().AllowAnyMethod().AllowAnyHeader()); //配置跨域 http://localhost:53649是前端页面地址,注意launchSettings.json中指定
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub("/chatHub"); //配置前端接口
});
}
}
}
后台项目就配置好了
创建ASP.NET Core Web 应用程序
在“解决方案资源管理器”中,右键单击项目,然后选择“添加”>“客户端库” 。
“提供程序”,选择“unpkg”>“库”,输入 @microsoft/signalr@latest
选择“选择特定文件”,展开“dist/browser”文件夹,然后选择“signalr.js”和“signalr.min.js”。
将“目标位置”设置为 wwwroot/js/signalr/,然后选择“安装”。
给项目Index.cshtml页面内容替换成
@page
User
Message
在 wwwroot/js 文件夹中,创建 chat.js 文件
"use strict";
//http://localhost:15931/chatHub是接口地址,自己注意配置
var connection = new signalR.HubConnectionBuilder().withUrl("http://localhost:15931/chatHub").build();
//Disable 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} 发送消息 ${message}`;
});
connection.on("ConnectMessage", function (Id, 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 = `连接标识 ${Id} ${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("HandMessage", user, message).catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});
给两个项目都启动,就是一个简单的signalr前后端分离Demo了,具体详细大家可以参考微软官方文档或者下载代码自己调试修改
官方文档地址 :https://docs.microsoft.com/zh-cn/aspnet/core/signalr/introduction?view=aspnetcore-5.0
gitee地址 https://gitee.com/gl125/signalr-demo
csdn资源下载 https://download.csdn.net/download/qq_36535245/20360402
.NET QQ技术交流群 681169497