


Detailed explanation of message push code using SignaiR and Push.js
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("我是一条新的推送消息!");//广播推送
var context = GlobalHost.ConnectionManager.GetConnectionContext<MyConnection1>();//获取你当前的Connection连接 context.Connection.Send(connectionId, "Welcome!");//单推事列
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!

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 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics











Use Firebase Cloud Messaging (FCM) to implement message push function in PHP applications. With the rapid development of mobile applications, real-time message push has become one of the indispensable functions of modern applications. Firebase Cloud Messaging (FCM) is a cross-platform messaging service that helps developers push real-time messages to Android and iOS devices. This article will introduce how to use FCM to implement message push function in PHP applications.

How to implement message push and notification reminders in uniapp With the rapid development of mobile Internet, message push and notification reminders have become indispensable functions in mobile applications. In uniapp, we can implement message push and notification reminders through some plug-ins and interfaces. This article will introduce a method to implement message push and notification reminder in uniapp, and provide specific code examples. 1. Message Push The premise for implementing message push is that we need a background service to send push messages. Here I recommend using Aurora Push.

1. Open the phone settings, click Applications, and click Application Management. 2. Find and click to enter the Amap. 3. Click Notification Management and turn off the Allow Notifications switch to turn off message push notifications. This article takes Honor magic3 as an example and is applicable to Amap v11.10 version of MagicUI5.0 system.

With the rapid development of mobile Internet and changes in user needs, the message push system has become an indispensable part of modern applications. It can realize instant notification, reminder, promotion, social networking and other functions to provide users and business customers with better services. experience and service. In order to meet this demand, this article will introduce how to use the PHP framework Lumen to develop an efficient message push system to provide timely push services. 1. Introduction to Lumen Lumen is a micro-framework developed by the Laravel framework development team. It is a

UniApp is a framework for developing cross-platform applications that can run on iOS, Android and Web platforms at the same time. When implementing the message push function, UniApp can cooperate with the back-end push service to realize the design and development of message push. 1. Design overview of message push To implement the message push function in UniApp, you need to design a push service to send push messages to the App. The push service needs to implement the following functions: establish a connection with the App and send messages.

Analysis of the relationship between PHP real-time communication function and message push middleware With the development of the Internet, the importance of real-time communication function in Web applications has become increasingly prominent. Real-time communication allows users to send and receive messages in real-time in applications, and can be applied to a variety of scenarios, such as real-time chat, instant notification, etc. In the field of PHP, there are many ways to implement real-time communication functions, and one of the common ways is to use message push middleware. This article will introduce the relationship between PHP real-time communication function and message push middleware, and how to use message push

Selection of message push service for developing real-time chat function in PHP Introduction: With the rapid development of the Internet, real-time communication has become an indispensable function for many websites and applications. In order to achieve real-time message push and real-time chat functions, it is crucial to choose the appropriate message push service. This article will introduce some commonly used message push services that are suitable for PHP development and provide relevant code examples. 1. Implementation of WebSocket protocol The WebSocket protocol is a TCP-based protocol specifically used to achieve real-time two-way communication.

Quick Start: Use Go language functions to implement simple message push functions In today's mobile Internet era, message push has become a standard feature of various APPs. Go language is a fast and efficient programming language, which is very suitable for developing message push functions. This article will introduce how to use Go language functions to implement a simple message push function, and provide corresponding code examples to help readers get started quickly. Before we begin, we need to understand the basic principles of message push. Generally, message push functionality requires two main components: push server
