SignalR指定用户推送

2024-06-10 09:58
文章标签 指定 用户 推送 signalr

本文主要是介绍SignalR指定用户推送,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

添加SignalR推送官方文档:
https://docs.microsoft.com/zh-cn/aspnet/core/signalr/groups?view=aspnetcore-5.0

项目安装Microsoft.AspNetCore.SignalR包

配置集线器类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SignalR;namespace WebNetCore5_Img_Storage.Handler
{//继承IUserIdProvider用于告诉SignalR连接用谁来绑定用户idpublic class GetUserId : IUserIdProvider{string IUserIdProvider.GetUserId(HubConnectionContext connection){//获取当前登录用户idstring userid = connection.GetHttpContext().Session.GetString("user_id");return userid;}}public class ChatHub : Hub{public async Task SendMessage(string user, string message){await Clients.All.SendAsync("ReceiveMessage", user, message);}//特定用户推送消息public async Task SendPrivateMessage(string user, string message){await Clients.User(user).SendAsync("ReceiveMessage", message);}}
}

C#推送代码

 public class FileUploadController : BaseController{private readonly IHubContext<ChatHub> hubContext;public FileUploadController(IHubContext<ChatHub> _hubContext){        hubContext = _hubContext;}public async Task<ActionResult> UploadBigFile(IFormFile file)
{//当前登录用户idstring loginUserId=Current.Id;//后台上传进度decimal process = Math.Round((decimal)fileNo * 100 / total_minio_file_count, 2);	 //推送消息到前端hubContext.Clients.User(loginUserId).SendAsync("ReceiveMessage", loginUserId, process);								
}

配置启动类注册IUserIdProvider的实例

   // This method gets called by the runtime. Use this method to add services to the container.public void ConfigureServices(IServiceCollection services){//解决中文输出后被编码了services.Configure<Microsoft.Extensions.WebEncoders.WebEncoderOptions>(options =>{options.TextEncoderSettings = new System.Text.Encodings.Web.TextEncoderSettings(System.Text.Unicode.UnicodeRanges.All);});//services.AddControllersWithViews();//添加全局筛选器:services.AddControllersWithViews(options =>{options.Filters.Add(typeof(CustomExceptionFilter));})//自定义格式化json使用Newtonsoft.Json.AddNewtonsoftJson();//services.addNewservices.AddRazorPages();//session配置缓存组件依赖,分布式缓存//services.AddDistributedMemoryCache();//会话存活时间,单位(秒)int sessionTime = 0;int.TryParse(MyConfigReader.GetConfigValue("session_live_time"), out sessionTime);if (sessionTime == 0){sessionTime = 7200;}services.AddSession(options =>{//设置cookie名称//options.Cookie.Name = ".AspNetCore.Session";//会话滑动过期时间,距下次访问最小时间,超过则session失效options.IdleTimeout = TimeSpan.FromSeconds(sessionTime);options.Cookie.HttpOnly = true;options.Cookie.IsEssential = true;});//业务层注入  //services.AddScoped<IImgBLL, ImgBLLImpl>();string path = AppDomain.CurrentDomain.BaseDirectory;Assembly bll_impl = Assembly.LoadFrom(path + "WebNetCore5_Img_Storage.BLL.dll");Assembly bll_interface = Assembly.LoadFrom(path + "WebNetCore5_Img_Storage.IBLL.dll");var typesInterface = bll_interface.GetTypes();var typesImpl = bll_impl.GetTypes();foreach (var item in typesInterface){var name = item.Name.Substring(1);string implBLLImpName = name + "Impl";var impl = typesImpl.FirstOrDefault(w => w.Name.Equals(implBLLImpName));if (impl != null){//services.AddTransient(item, impl);//services.AddSingleton(item, impl);services.AddScoped(item, impl);}}//数据层注册Assembly dalAssemblys = Assembly.LoadFrom(path + "WebNetCore5_Img_Storage.DAL.dll");Assembly dalInterface = Assembly.LoadFrom(path + "WebNetCore5_Img_Storage.IDAL.dll");var dalTypesImpl = dalAssemblys.GetTypes();var dalTypesInterface = dalInterface.GetTypes();foreach (var item in dalTypesInterface){var name = item.Name.Substring(1);string implDalName = name + "Impl";var impl = dalTypesImpl.FirstOrDefault(w => w.Name.Equals(implDalName));if (impl != null){//services.AddTransient(item, impl);services.AddScoped(item, impl);}}services.AddMvcCore();//用户IUserIdProvider实例注册services.AddScoped<Microsoft.AspNetCore.SignalR.IUserIdProvider, GetUserId>();//SignalR添加到服务services.AddSignalR();}public void Configure(IApplicationBuilder app, IWebHostEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}else{app.UseExceptionHandler("/Error");}app.UseHttpsRedirection();app.UseStaticFiles(new StaticFileOptions(){//不限制content-type下载ServeUnknownFileTypes = true,配置的虚拟路径映射//RequestPath = "/local",物理地址//FileProvider = new Microsoft.Extensions.FileProviders.PhysicalFileProvider("D:\\Work\\西南油气田图库系统\\WebNetCore5_Img_Storage\\WebNetCore5_Img_Storage\\bin\\Debug\\net5.0"),});app.UseRouting();//app.UseAuthentication();app.UseAuthorization();app.UseSession();//app.UseResponseCaching();//app.UseResponseCompression();//用MVC模式, 针对services的services.AddControllersWithViews();app.UseEndpoints(endpoints =>{//endpoints.MapDefaultControllerRoute();endpoints.MapRazorPages();endpoints.MapControllerRoute(name: "default",pattern: "{controller=Home}/{action=Index}/{id?}");endpoints.MapHub<ChatHub>("/chathub");});

前端界面js代码

    <script src="~/lib/microsoft/signalr/dist/browser/signalr.min.js"></script>//signalR推送消息,用于显示后台实时处理进度var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();connection.on("ReceiveMessage", function (user, message) {console.log("user=" + user + ",message=" + message);//后台上传视频到文件系统进度值$("#back_process_value").html(message+"%");});connection.start().then(function () {console.log("signalR推送连接成功");}).catch(function (err) {console.error("signalR推送连接异常");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();//});

这篇关于SignalR指定用户推送的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1047847

相关文章

详解如何在SpringBoot控制器中处理用户数据

《详解如何在SpringBoot控制器中处理用户数据》在SpringBoot应用开发中,控制器(Controller)扮演着至关重要的角色,它负责接收用户请求、处理数据并返回响应,本文将深入浅出地讲解... 目录一、获取请求参数1.1 获取查询参数1.2 获取路径参数二、处理表单提交2.1 处理表单数据三、

Python如何调用指定路径的模块

《Python如何调用指定路径的模块》要在Python中调用指定路径的模块,可以使用sys.path.append,importlib.util.spec_from_file_location和exe... 目录一、sys.path.append() 方法1. 方法简介2. 使用示例3. 注意事项二、imp

CentOS和Ubuntu系统使用shell脚本创建用户和设置密码

《CentOS和Ubuntu系统使用shell脚本创建用户和设置密码》在Linux系统中,你可以使用useradd命令来创建新用户,使用echo和chpasswd命令来设置密码,本文写了一个shell... 在linux系统中,你可以使用useradd命令来创建新用户,使用echo和chpasswd命令来设

Pandas利用主表更新子表指定列小技巧

《Pandas利用主表更新子表指定列小技巧》本文主要介绍了Pandas利用主表更新子表指定列小技巧,通过创建主表和子表的DataFrame对象,并使用映射字典进行数据关联和更新,实现了从主表到子表的同... 目录一、前言二、基本案例1. 创建主表数据2. 创建映射字典3. 创建子表数据4. 更新子表的 zb

SpringBoot UserAgentUtils获取用户浏览器的用法

《SpringBootUserAgentUtils获取用户浏览器的用法》UserAgentUtils是于处理用户代理(User-Agent)字符串的工具类,一般用于解析和处理浏览器、操作系统以及设备... 目录介绍效果图依赖封装客户端工具封装IP工具实体类获取设备信息入库介绍UserAgentUtils

Mysql用户授权(GRANT)语法及示例解读

《Mysql用户授权(GRANT)语法及示例解读》:本文主要介绍Mysql用户授权(GRANT)语法及示例,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录mysql用户授权(GRANT)语法授予用户权限语法GRANT语句中的<权限类型>的使用WITH GRANT

在Android平台上实现消息推送功能

《在Android平台上实现消息推送功能》随着移动互联网应用的飞速发展,消息推送已成为移动应用中不可或缺的功能,在Android平台上,实现消息推送涉及到服务端的消息发送、客户端的消息接收、通知渠道(... 目录一、项目概述二、相关知识介绍2.1 消息推送的基本原理2.2 Firebase Cloud Me

使用Python实现获取网页指定内容

《使用Python实现获取网页指定内容》在当今互联网时代,网页数据抓取是一项非常重要的技能,本文将带你从零开始学习如何使用Python获取网页中的指定内容,希望对大家有所帮助... 目录引言1. 网页抓取的基本概念2. python中的网页抓取库3. 安装必要的库4. 发送HTTP请求并获取网页内容5. 解

Python实现合并与拆分多个PDF文档中的指定页

《Python实现合并与拆分多个PDF文档中的指定页》这篇文章主要为大家详细介绍了如何使用Python实现将多个PDF文档中的指定页合并生成新的PDF以及拆分PDF,感兴趣的小伙伴可以参考一下... 安装所需要的库pip install PyPDF2 -i https://pypi.tuna.tsingh

mysql删除无用用户的方法实现

《mysql删除无用用户的方法实现》本文主要介绍了mysql删除无用用户的方法实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 1、删除不用的账户(1) 查看当前已存在账户mysql> select user,host,pa