


ASP.NET SignalR is a library for ASP.NET developers that simplifies the process for developers to add real-time web functionality to their applications. Those who are interested can find out.
1. Use background
1. What is SignalR?
ASP.NET SignalR is a library for ASP.NET developers that simplifies the process of adding real-time web functionality to applications. A real-time web feature is a feature where server code can push content to a connected client as soon as it becomes available, rather than having the server wait for the client to request new data.
2.What is Push.js? [The browser needs to support H5Notifications]
Notifications is translated as notification. So what do Push.js notifications look like? See the picture below: most of them appear in the lower right corner of the screen.
Need permission:
3. Many times we can only use polling to display data. Update and message push. So I thought about whether there is a way to synchronize the client-side update when the server-side data is updated.
2. Start deploying a SignalR project [using mvc]
1. Create a new mvc project
........................
2. Import the program package [Vs2015]
Tools->NuGet Package Manager-> Package Management Console->Install-Package Microsoft.AspNet.SignalR->WaitingInstallationSuccessful
3. Create a new hub class
project->right-click->Add->New item->SignalR->SignalR permanent link class->Save->[Take MyConnection1 as Example] MyConnection1
public class MyConnection1 : PersistentConnection { /// <summary> /// 发送消息 /// </summary> /// <param name="request"></param> /// <param name="connectionId"></param> /// <returns></returns> protected override Task OnConnected(IRequest request, string connectionId) { Debug.WriteLine(connectionId); return Connection.Send(connectionId, "Welcome!");//单推事列 } /// <summary> /// 接受客户端消息 /// </summary> /// <param name="request"></param> /// <param name="connectionId"></param> /// <param name="data"></param> /// <returns></returns> protected override Task OnReceived(IRequest request, string connectionId, string data) { Debug.WriteLine(data); return Connection.Broadcast(data);//广播 } /// <summary> /// 掉线 /// </summary> /// <param name="request"></param> /// <param name="connectionId"></param> /// <param name="stopCalled"></param> /// <returns></returns> protected override Task OnDisconnected(IRequest request, string connectionId, bool stopCalled) { Debug.WriteLine("掉线"); return base.OnDisconnected(request, connectionId, stopCalled); } /// <summary> /// 重连 /// </summary> /// <param name="request"></param> /// <param name="connectionId"></param> /// <returns></returns> protected override Task OnReconnected(IRequest request, string connectionId) { Debug.WriteLine("重连"); return base.OnReconnected(request, connectionId); } }
4. Create a new Owin Startup class[SignalR follows the Owin standard, Startup is the startup of the component, the Startup class will exist by default, just modify it]
We add the following code to the Configuration
public void Configuration(IAppBuilder app) { app.MapSignalR<MyConnection1>("/myconnection"); }
Explanation: When accessing myconnection, MyConnection1 is triggered
5. Add client [h5]
@{ ViewBag.Title = "Home Page"; Layout = null; } <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <meta charset="utf-8" /> </head> <body> <script src="~/Scripts/jquery-1.10.2.js"></script> <script src="~/Scripts/jquery.signalR-2.2.1.js"></script> <script type="text/javascript"> var conn = $.connection("/myconnection"); conn.start().done(function (data) { console.log("已连接服务器,当前GUID为" + data.id); conn.send("To Admin");//发送给服务器 }); //接受服务器的推送 conn.received(function (data) { console.log("服务器返回消息: " + data); }); </script> </body> </html>
6.Start the project Open the browser console, you will find the picture below, which means you have completed the first step.
7. Next we need to prepare push.js
Download address github.com/Nickersoft/push.js
8. Quote js
<script src="../Js/push.js"></script>
9. Create a new js push demo
function push(data, url, img) { var imgurl = img != "" ? img : "../Images/icon.png"; Push.create("新通知", { body: data, icon: imgurl, requireInteraction: true, onClick: function () { window.focus(); this.close(); window.location.href =url; } }); }
Explanation: data: is the message content
url: The link entered by clicking on the notification
img: The picture address displayed for the notification
requireInteraction: When set to true, unless the user manually closes it Or click the notification, otherwise the notification will not close. If you need to set the disappearing time, please replace this attribute with timeout: 5000 in milliseconds
Other events Please read: www.npmjs.com/package/push.js
10. Combine the two
//实时推送 var conn = $.connection("/myconnection"); conn.start().done(function (data) { console.log("已连接服务器,当前GUID为" + data.id); }); //接受服务器的推送 conn.received(function (msg) { console.log("服务器返回消息: " + msg); if (msg != "") { push(msg, "#", "") } });
11. The effect is as follows:
var context = GlobalHost.ConnectionManager.GetConnectionContext<MyConnection1>();//获取你当前的Connection连接 context.Connection.Broadcast("我是一条新的推送消息!");//广播推送Single push:
var context = GlobalHost.ConnectionManager.GetConnectionContext<MyConnection1>();//获取你当前的Connection连接 context.Connection.Send(connectionId, "Welcome!");//单推事列connectionId: is the GUID assigned by the server to each client
Li Yanhui ASP basic video tutorial
The above is the detailed content of Detailed explanation of message push code using SignaiR and Push.js. For more information, please follow other related articles on the PHP Chinese website!

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

C# is not always tied to .NET. 1) C# can run in the Mono runtime environment and is suitable for Linux and macOS. 2) In the Unity game engine, C# is used for scripting and does not rely on the .NET framework. 3) C# can also be used for embedded system development, such as .NETMicroFramework.

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.

C# is a programming language, while .NET is a software framework. 1.C# is developed by Microsoft and is suitable for multi-platform development. 2..NET provides class libraries and runtime environments, and supports multilingual. The two work together to build modern applications.

C#.NET is a powerful development platform that combines the advantages of the C# language and .NET framework. 1) It is widely used in enterprise applications, web development, game development and mobile application development. 2) C# code is compiled into an intermediate language and is executed by the .NET runtime environment, supporting garbage collection, type safety and LINQ queries. 3) Examples of usage include basic console output and advanced LINQ queries. 4) Common errors such as empty references and type conversion errors can be solved through debuggers and logging. 5) Performance optimization suggestions include asynchronous programming and optimization of LINQ queries. 6) Despite the competition, C#.NET maintains its important position through continuous innovation.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.
