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代碼:
using Microsoft.Extensions.Hosting; using System; using System.Threading; using System.Threading.Tasks; namespace YiSha.Admin.Web { public class PopupMessage : BackgroundService { protected override async Task 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中引入
<script src="~/yisha/js/SignalR/signalr.js"></script> <script src="~/yisha/js/iziToast/iziToast.js" type="text/javascript"></script>
在index.cshtml的<script>中添加如下代碼:(其中【對接收到的消息進行處理、顯示】是彈窗消息插件調用方法,彈窗消息插件的其他細節在本文的最后給與詳細介紹)
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: [ ['<button>Photo</button>', 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) { return console.error(err.toString()); }); async function start() { 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 IHubContext<ChatHub> HC; private IHubContext<ChatHub> _hubContext; public HomeController(IHubContext<ChatHub> hubContext) { this._hubContext = hubContext; HC = hubContext; } public async Task<IActionResult> PopupMessage(string message) { 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<Microsoft.Extensions.Hosting.IHostedService, PopupMessage>();
在startup.cs的Configure中添加如下代碼:
app.UseEndpoints(endpoints => { endpoints.MapHub<ChatHub>("/chathub"); });
至此,SignalR的整個處理過程就完成了
下面介紹一下前端消息彈窗插件的實現方法,非常美觀實用(下載地址:https://www.jq22.com/jquery-info11777)
1、插件下載及導入項目
2、在index的模板中引入插件CSS
<link rel="stylesheet" href="~/yisha/css/iziToast/iziToast.min.css"> <link rel="stylesheet" href="~/yisha/css/iziToast/demo.css">
3、在index中引入插件js(參見上面第5步)
<script src="~/yisha/js/iziToast/iziToast.js" type="text/javascript"></script>
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: [ ['<button>Photo</button>', 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' });
此代碼已測試成功,如果有問題請反饋,如果覺得對你有幫助請點擊【推薦】謝謝!