ASP. NET SignaiR implements Real-Time Message Push, and uses Push. js to implement sample code for notification, signairpush. js

Source: Internet
Author: User

ASP. NET SignaiR implements Real-Time Message Push, and uses Push. js to implement sample code for notification, signairpush. js

I. background

1. What is SignalR?

ASP. NET SignalR is a library provided by ASP. NET developers. It simplifies the process for developers to add real-time Web functions to applications. The real-time Web function refers to a function that allows the server code to push content immediately when the connected client becomes available, rather than waiting for the server to wait for the client to request new data.

2. What is Push. js? [Requires the browser to support H5Notifications]

Notifications are translated as Notifications. So what is the notification of Push. js? See: Most of the notifications appear in the lower right corner of the screen.

Yes:

3. In many cases, we can only use polling to update data presentation and push messages. So I thought there was a way to synchronously update the client when updating the server data.

2. Start to deploy a SignalR project [Use mvc]

1. Create an mvc Project

.....................

2. Import the package [Vs2015]

Tools-> NuGet Package Manager-> Package management console-> Install-Package Microsoft. AspNet. SignalR-> wait until installation is successful

3. Create a hub class

Project-> right-click-> Add-> new item-> SignalR permanent link class-> Save-> [take MyConnection1 as an example] MyConnection1

Public class MyConnection1: persistentConnection {// <summary> /// send a message // </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! "); // Single push column} // <summary> // accept client message // </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 ); // broadcast} // <summary> // dropped/// </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 ("dropped"); return base. onDisconnected (request, connectionId, stopCalled );} /// <summary> /// reconnection // </summary> /// <param name = "request"> </param> /// <param name = "connectionId"> </param> // <returns> </returns> protected override Task OnReconnected (IRequest request, string connectionId) {Debug. writeLine ("reconnect"); return base. onReconnected (request, connectionId );}}

4. Create the Owin Startup class[SignalR follows the Owin standard, and Startup is the start of the component. By default, the Startup class exists. You only need to modify it]

Add the following code to Configuration:

public void Configuration(IAppBuilder app)    {      app.MapSignalR<MyConnection1>("/myconnection");    }

Explanation: MyConnection1 is triggered when myconnection is accessed.

5. Add the client [h5]

@ {ViewBag. Title = "Home Page"; Layout = null ;}<! DOCTYPE html> 

6. Start the project and open the browser console. You will find that you have completed the first step.

7. Now we need to prepare push. js

Https://github.com/Nickersoft/push.js

8. Reference js

<script src="../Js/push.js"></script>

9. Create a js push demo

Function push (data, url, img) {var imgurl = img! = ""? Img :".. /Images/icon.png "; Push. create ("new notification", {body: data, icon: imgurl, requireInteraction: true, onClick: function () {window. focus (); this. close (); window. location. href = url ;}});}

Description: data indicates the message content.

Url: the link for clicking the notification

Img: The image address displayed for the notification.

RequireInteraction: if it is set to true, the notification will not be closed unless you manually close or click the notification. To set the disappearance time, replace this attribute with timeout: 5000 in milliseconds.

For other events please read: https://www.npmjs.com/package/push.js

10. combine the two

// Real-time push var conn = $. connection ("/myconnection"); conn. start (). done (function (data) {console. log ("Connected Server, current GUID is" + data. id) ;}); // receives the push conn from the server. received (function (msg) {console. log ("server response message:" + msg); if (msg! = "") {Push (msg ,"#","")}});

11. The results are as follows:

12. Implement active server push. Only broadcast is introduced now. The single push principle is consistent.

It can be divided into two modes: Broadcast and single push.

Broadcast:

Var context = GlobalHost. ConnectionManager. GetConnectionContext <MyConnection1> (); // obtain your current Connection context. Connection. Broadcast ("I am a new push message! "); // Broadcast push

Single push:

Var context = GlobalHost. ConnectionManager. GetConnectionContext <MyConnection1> (); // obtain your current Connection context. Connection. Send (connectionId, "Welcome! "); // Single push Column

ConnectionId: GUID allocated by the server for each client

13. The effect is as follows:

In this way, when the server processes a task, it can call broadcast to actively push data to the client for real-time data updates and message pushing.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.