C#(一沙框架) .net core3.1 SignalR 服务端推送消息至客户端的实现方法,用弹窗插件进行显示,非常美观实用

运行效果:

1、安装Microsoft.AspNetCore.SignalR(安装方法自行百度)

2、引入chat.js、signalr.js(请自行百度下载)

3、新建ChatHub.cs

ChatHub.cs代码:

using Microsoft.AspNetCore.SignalR;

using System.Threading.Tasks;

namespace YiSha.Admin.Web

{

public class ChatHub : Hub

{

public async Task SendMessage(string msg)

{

await Clients.All.SendAsync("ReceiveMessage", msg);

}

}

}

4、服务端后台处理程序,新建MyBackgroundService.cs

MyBackgroundService.cs代码:

usingMicrosoft.Extensions.Hosting;usingSystem;usingSystem.Threading;usingSystem.Threading.Tasks;namespaceYiSha.Admin.Web

{public classPopupMessage : BackgroundService

{protected override asyncTask ExecuteAsync(CancellationToken stoppingToken)

{while (!stoppingToken.IsCancellationRequested)

{try{//需要执行的任务

var pm = new Controllers.HomeController(Controllers.HomeController.HC);//HC为Controller中定义的ChatHub的静态上下文变量//弹窗消息处理

await pm.PopupMessage(DateTime.Now.ToString() + "hahaha");

}catch(Exception ex)

{//LogHelper.Error(ex.Message);

}await Task.Delay(5000, stoppingToken);//等待5秒

}

}

}

}

5、前端页面(整个项目的首页index)

在index.cshtml中引入

在index.cshtml的中添加如下代码:(其中【对接收到的消息进行处理、显示】是弹窗消息插件调用方法,弹窗消息插件的其他细节在本文的最后给与详细介绍)

var connection = new signalR.HubConnectionBuilder().withUrl("/chathub").build();

connection.on("ReceiveMessage", function(data) {var encodedMsg = data.msg;//获取接收到的消息内容

//对接收到的消息进行处理、显示

iziToast.success({

title:'OK',

message: encodedMsg,

position:'bottomRight',

transitionIn:'bounceInUp',//transitionIn: 'flipInX',fadeInDown

transitionOut: 'flipOutX',//iconText: 'star',

onOpen: function(){

console.log('callback abriu! success');

},

onClose:function(){

console.log("callback fechou! success");

},

buttons: [

['Photo', function(instance, toast) {

}],

]

});

iziToast.warning({

title:'Caution',

message:'You forgot important data',

position:'bottomRight',

transitionIn:'bounceInUp',

transitionOut:'flipOutX'});

iziToast.error({

title:'Error',

message:'Illegal operation',

position:'bottomRight',

transitionIn:'bounceInUp'});

});

connection.start().then(function() {//document.getElementById("sendButton").disabled = false;

}).catch(function(err) {returnconsole.error(err.toString());

});

asyncfunctionstart() {try{

await connection.start({ transport: ['webSockets'] });

console.log("connected");

}catch(err) {

console.log(err);

setTimeout(()=> start(), 5000);

}

};

connection.onclose(async ()=>{

start();

});

6、index对应的controller

在index对应的controller中添加如下代码:

#region SignalR

public static IHubContextHC;private IHubContext_hubContext;public HomeController(IHubContexthubContext)

{this._hubContext =hubContext;

HC=hubContext;

}public async Task PopupMessage(stringmessage)

{if (_hubContext == null) return Json(new { code = "0", msg = ""});await _hubContext.Clients.All.SendAsync("ReceiveMessage", new { msg =message });return Json(new { code = "success", msg = "发送成功"});

}#endregion

7、修改startup.cs

在startup.cs的ConfigureServices中添加如下代码:

services.AddSignalR();

services.AddSingleton();

在startup.cs的Configure中添加如下代码:

app.UseEndpoints(endpoints =>{

endpoints.MapHub("/chathub");

});

至此,SignalR的整个处理过程就完成了

下面介绍一下前端消息弹窗插件的实现方法,非常美观实用(下载地址:https://www.jq22.com/jquery-info11777)

1、插件下载及导入项目

2、在index的模板中引入插件CSS

3、在index中引入插件js(参见上面第5步)

4、在index中调用弹窗显示方法(参见上面第5步)

//对接收到的消息进行处理、显示

iziToast.success({

title:'OK',

message: encodedMsg,

position:'bottomRight',

transitionIn:'bounceInUp',//transitionIn: 'flipInX',fadeInDown

transitionOut: 'flipOutX',//iconText: 'star',

onOpen: function(){

console.log('callback abriu! success');

},

onClose:function(){

console.log("callback fechou! success");

},

buttons: [

['Photo', function(instance, toast) {

}],

]

});

iziToast.warning({

title:'Caution',

message:'You forgot important data',

position:'bottomRight',

transitionIn:'bounceInUp',

transitionOut:'flipOutX'});

iziToast.error({

title:'Error',

message:'Illegal operation',

position:'bottomRight',

transitionIn:'bounceInUp'});

此代码已测试成功,如果有问题请反馈,如果觉得对你有帮助请点击【推荐】谢谢!

nett服务器接收消息的方法,C#(一沙框架) .net core3.1 SignalR 服务端推送消息至客户端的实现方法,用弹窗插件进行显示,非常美观实用...相关推荐

  1. springboot 实现服务端推送消息

    文章目录 前言 一.关于SSE 1. 概念介绍 2. 特点分析 3. 应用场景 二.SpringBoot实现 三.前端vue调用 四.一些问题 前言 服务端推送消息我们采用SSE方式进行推送. 一.关 ...

  2. Java 服务端推送消息有那么难吗?

    点击蓝色"程序猿DD"关注我 回复"资源"获取独家整理的学习资料! 转自公众号:码农小胖哥 今天项目经理交给我一个开发任务.如果有人在前台下了订单就给后台仓库管 ...

  3. Android端推送消息之极光推送

    推送方式 轮询 --实现方式: 周期性主动获取网络中的数据; --缺点: 费电, 费流量; SMS --实现方式: 服务器端向手机端发送短信, 手机监听短信广播, 将拦截的短信信息进行显示; --优点 ...

  4. 个推PC端推送消息至App

    本文以个推透传消息为例: 个推SDK下载地址:点击打开链接 开发准备见官方文档:http://docs.igetui.com/pages/viewpage.action?pageId=590077 类 ...

  5. 小程序表单提交,服务端推送模板消息通知

    1.小程序按钮表单,提交formid和openid 注:https://blog.csdn.net/qq_38191191/article/details/80982732 2.发送网络请求(小程序点 ...

  6. server端推送消息机制

    推送技术相关请参加WIKI: https://zh.wikipedia.org/wiki/%E6%8E%A8%E9%80%81%E6%8A%80%E6%9C%AF 场景: 监控系统:后台硬件温度.电压 ...

  7. uniapp消息推送(个推-PHP服务端推送)

    <?phpnamespace app\service;use think\facade\Cache;/*** Class SinglePushService* 个推文档 https://docs ...

  8. 关注微信公众号并接收服务端推送通知

    这是一篇写在公司内网confluence上的文章,今天打开博客发现好久没有更新了,偷个懒直接来个搬运. 1.应用场景 终端用户关注客户微信公众号后,在公众号上可以接收到服务端发来的关联设备的报警信息 ...

  9. 微信小程序使用微信服务号推送消息

    使用前提 查看自己是否有发送消息模板接口的权限 点击 消息模板(业务通知)查看相关的api文档 开发版本 开发工具 :IntelliJ IDEA 2022.2.1 数据库 :MySQL Server ...

最新文章

  1. python科学计数法转换_对比Python学习Go 基本数据结构
  2. Windows Azure Service Bus (5) 主题(Topic) 使用VS2013开发Service Bus Topic
  3. 关系到了冰点_疫情下半场,如何修复跌至冰点的亲子关系,让自己和家人活出幸福感?...
  4. mysql中一个表怎么查询多以上的信息,MySQL怎么样实现多个表的或查询?
  5. 鸿蒙tv系统安装,运行第一个鸿蒙tv应用
  6. sessionId与cookie 的关系(百度文库)
  7. SQL Server 数据库没有有效所有者的三种解决办法
  8. 给xen虚拟机添加硬盘分区格式化
  9. 一起看2018阿里技术参考图册(算法篇)
  10. Python中List,tuple,Dictionary之间的区别
  11. 重振pointnet++雄风!PointNeXt: Revisiting PointNet++ with ImprovedTraining and Scaling Strategies
  12. 员工符合签订无固定期限劳动合同的条件,这种情况单位有权不予续签吗?
  13. 苹果退款_退货与退款 - 购买帮助 - Apple (中国大陆)
  14. php又拍云,申请又拍云云存储教程(PHP V3.80+)
  15. Spring Boot制作个人博客-标签页
  16. 学术论文摘要写作技巧:
  17. spaCy的方法进行训练一个新的招投标实体标注模型
  18. 一台计算机有多少公顷,亩换算成公顷(公顷换算成亩的计算器)
  19. 4.2 理性看考试——《逆袭大学》连载
  20. 中文信息处理——纵览与建议

热门文章

  1. 2019最新计算机毕业设计-题目汇总大全-系列4
  2. 明星也有被「老赖」羁绊的困扰?
  3. js中的的GO和AO
  4. charles手机抓包教程
  5. python编程语言创始人-程序员都秃顶?Python创始人笑了,养生还得学这门语言
  6. ShanaEncoder 官网链接
  7. 2013年6月《棱镜透视了什么?》
  8. python小小爬虫(一)—— 爬取学校官网通知(仅作为练习使用)
  9. el-table滚动条被挡住的问题
  10. LET: Linguistic Knowledge Enhanced Graph Transformer for Chinese Short Text Matching学习笔记