Implement Message push by Signalr and message by signalr

Source: Internet
Author: User
Tags sendmsg

Implement Message push by Signalr and message by signalr

I. Preface

Most systems seem to have the function of obtaining messages, but these message sources are not real-time. For example, if you open two browsers and log on with two different accounts, if you use one account to send messages to another account, but do not receive messages in real time, you must manually refresh the page with F5 to display your messages. In this way, the user experience is poor. I have read the Learning hard article about Signalr, And I have used the function of getting real-time messages in my project. However, in our project, we use the js Code setinterval method to refresh and read data in one second, this seriously adds burden to the server and affects system performance! So I have studied it a little. Here are some of my understandings. If something is wrong, please make an axe!

II. Implementation Principle

Next, let's talk about our understanding of Signalr. Signalr can perform remote distributed real-time communication, which is implemented using remote proxy. There are two internal objects, and the first is Persisten Connection, it is used for persistent connections between the client and the server, and the second is the Hub object. It is mainly used for information interaction and pushes data from the server to the client. The general principle is as follows:

1. The client establishes a connection with the server.

2. The client calls the server-side method.

3. the server sends a request, responds to the data, and then pushes the data to the client.

3. Implement Message push using Signalr

The specific operations are as follows:

1. Create an application. Here I create an MVC application.

2. Reference related components. Right-click to reference and choose manage Nuget packages.

3. Search for Signalr ,:

Click Install. Two js files are automatically generated in the Scripts folder of the application ,:

4. Add an integrator class

5. Register signalr/hubs and add the following code to Startup. cs:

6. Create a new controller MessageController, and then create two new view Methods SendMessage and ReceiveMessage in the Controller. To make the effect more intuitive, one page is used to send messages, and one page is used to receive messages ,:

7. Add the code in the MyHub class of the new integrator class:

(In particular, the InsertMsg method here is mainly to save the message information sent from the client to the database for easy reading of the message. In order to quickly create a database table, the code first method is used to create a table. You can create a table in any way .)

Namespace Signalr. models {[HubName ("MyHub")] public class MyHub: Hub {MessageDbContext _ db = new MessageDbContext (); public void Send (string title, string message) {this. insertMsg (title, message); // call the sendMessage method Clients of all Clients. all. sendMessage (message);} private void InsertMsg (string title, string message) {Message msg = new Message (); msg. title = title; msg. msgContent = message; _ db. messages. add (msg); _ db. saveChanges ();}}}

Table Structure:

8. Controller MessageController background code

public class MessageController : Controller    {      private MessageDbContext _db = new MessageDbContext();        public ActionResult SendMessage()        {            return View();        }        public ActionResult ReceiveMessage()        {            return View();        }        [HttpPost]        public JsonResult MsgCount()          {            var count = this._db.Messages.Where(p=>p.IsRead==0).Count();          return Json(new {count=count},JsonRequestBehavior.AllowGet);        }    }

 

9. Front-end Page code (SendMessage. cshtml)

@ {ViewBag. Title = "Send message" ;}< title> send message </title> <script src = "~ /Scripts/jquery-1.10.2.js "> </script> <script src = "~ /Scripts/jquery. signalR-2.2.0.min.js "> </script> <script src = "~ /Signalr/hubs "> </script> <script type =" text/javascript ">$ (function () {// reference the automatically generated hub proxy var chat =$. connection. myHub; // defines the client sendMessage called by the server to display the new message chat. client. sendMessage = function (title, message) {// send the received message to the page sendMsg () ;}; // the connection of the integrator starts $. connection. hub. start (). done (function () {sendMsg (); // The service connection is complete. register the send button and click event $ ('# sendmessage '). click (function () {// call the Send method chat of the server hub. server. send ($ ("# title "). val (), $ ('# message '). val ();}); function sendMsg () {var options = {url: '/Message/MsgCount', type: 'post', success: function (data) {$ ("# count" example .html (data. count) ;}}; $. ajax (options) ;}</script> 

10. Front-end Page code (ReceiveMessage. cshtml)

@ {ViewBag. Title = "Receive message" ;}< title> Accept message </title> <script src = "~ /Scripts/jquery-1.10.2.js "> </script> <script src = "~ /Scripts/jquery. signalR-2.2.0.min.js "> </script> <script src = "~ /Signalr/hubs "> </script> <script type =" text/javascript ">$ (function () {// reference the automatically generated hub proxy var chat =$. connection. myHub; // defines the client sendMessage called by the server to display the new message chat. client. sendMessage = function (title, message) {// message MsgCount () sent to the page; var html = "<div> title:" + title + "message content: "+ message +" </div> "; $ (" # msgcontent "). after (html) ;}; // The Integrator connection starts $. connection. hub. start (). done (function () {MsgCount () ;}); function MsgCount () {var options = {url: '/Message/MsgCount', type: 'post ', async: false, data: {title: $ ("# title "). val (), msgcontent: $ ("# sendmessage "). val ()}, success: function (data) {$ ("# count" rows .html (data. count) ;}}; $. ajax (options) ;}</script> 

 

Okay, I'm done. You may be wondering where this js file is referenced.

Click F12 to view the running page. It will automatically generate a js file here. You only need to reference this path on the page.

Iv. Page Effects(It's time to witness the miracle, hahaha ~~~)

To make the page more intuitive, I use IE to open the SendMessage. cshtml page and Google to open the ReceiveMessage. cshtml page.

 

Statement of rights and responsibilities

Author: SportSky Source: http://www.cnblogs.com/sportsky/
The copyright of this article is shared by the author and the blog Park. You are welcome to repost this article. However, you must retain this statement without the author's consent and provide a clear link to the original article on the article page. Otherwise, you will be held legally liable. If you think it is helpful, click [recommendation] in the lower right corner. We hope that we can continue to provide you with good technical articles! Want to make progress with me? Then [follow] Me

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.