SIGNALR implementing Message Push

Source: Internet
Author: User

First, preface

Most systems seem to have the ability to get messages, but these sources are not real-time, such as you open two browser, with two different accounts to send messages to another account, but do not receive real-time messages, you must manually F5 refresh the page to display their own messages, It feels like the user experience is not very good. Before looking at learning hard about SIGNALR article, just own project useful to get real-time message function, however, our project is to use the JS code setinterval method for 1 seconds to refresh the read data, so serious to add burden on the server side, affecting system performance! So I have a little research, the following is some of their own understanding, if there is not the right place, please everyone to treatise!

Second, the realization principle

The following talk about their understanding of SIGNALR, SIGNALR can be remote distributed real-time communication, are using remote proxy, which has two large internal objects, the first is Persisten Connection, for the client and server-side persistent connection, The second is the hub (hub) object, mainly for information interaction, the server-side data push (push) to the client, the general principle is as follows:

1, the client establishes the connection with the server side

2, the client calls the server-side method

3, the server side sends the request through the client, the response data, then pushes the data to the client

Iii. SIGNALR implementation of message push

The following actions are implemented:

1. Create an application that I created here is an MVC application

2, reference related components, right-click reference "Select Manage NuGet Packages

3, Search signalr,:

Click Install, in the application's Scripts folder will automatically generate two JS files:

4. Adding an Integrator class

5, register signalr/hubs, add the following code inside the Startup.cs

6, the new controller Messagecontroller, and then in the controller to create a new two view methods SendMessage and ReceiveMessage, in order to make the effect more intuitive, a page for sending messages, a page for receiving messages:

7. Add code to the Myhub class of the Integrator class we just created:

(in particular, the Insertmsg method here is mainly to save the message sent by the client to the database, easy to read the message, in order to quickly create a database table, I used the code first method to create, as to how you want to create the table, it is possible.) )

namespacesignalr.models {[Hubname ("Myhub")]     Public classMyhub:hub {messagedbcontext _db=NewMessagedbcontext ();  Public voidSend (stringTitlestringmessage) {             This.            Insertmsg (title, message); //Call the SendMessage method for all clientsClients.All.sendMessage (message); }        Private voidInsertmsg (stringTitlestringmessage) {Message msg=NewMessage (); Msg. Title=title; Msg. Msgcontent=message; _db.            Messages.add (msg); _db.        SaveChanges (); }    }}

Table structure:

8. Front 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 () {//referencing the auto-generated hub agent        varChat =$.connection.        Myhub; //define client SendMessage for server-side calls to display new messagesChat.client.sendMessage =function (title, message) {//send a received message to a pagesendmsg ();        }; //Integrator Connection started$.connection.hub.start (). Done (function () {sendmsg (); //Service Connection complete, register click event for send button$('#sendmessage'). Click (function () {//call the Send method of the server-side hubChat.server.send ($ ("#title"). Val (), $ ('#message'). Val ());        });    });    }); function sendmsg () {varOptions ={URL:'/message/msgcount', type:'Post', Success:function (data) {$ ("#count"). HTML (data.count);        }        };    $.ajax (options); }</script>Send Message"color:red; font-size:30px;"Id="Count"></span>Strip</div><p> <div>Title:<input type="text"Id="title"/> </div> <br/><br/> <div>content:<textarea id="message"Rows="4"cols=" -"></textarea> </div> <br/><br/> <div> <input type="Button"Id="SendMessage"Value="Send"/> </div></p>

9. Front page code (receivemessage.cshtml)

@{Viewbag.title="Accept Message";}<title> Receive Messages </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 () {//referencing the auto-generated hub agent        varChat =$.connection.        Myhub; //define client SendMessage for server-side calls to display new messagesChat.client.sendMessage =function (title, message) {//send a received message to a pageMsgcount (); varHTML ="<div> Title:"+ title +"Message content:"+ Message +"</div>"; $("#msgcontent"). After (HTML);        }; //Integrator Connection started$.connection.hub.start (). Done (function () {msgcount ();    });    }); function Msgcount () {varOptions ={URL:'/message/msgcount', type:'Post',            Async:false, data: {title: $ ("#title"). Val (), Msgcontent: $ ("#sendmessage"). Val ()}, Success:function (data) {$ ("#count"). HTML (data.count);        }        };    $.ajax (options); }</script>Receiving Messages"color:red; font-size:30px; margin-right:10px;"Id="Count"></span>Strip<br/> <br/> <div id="msgcontent"></div></div>

Well, done, maybe you have a little doubt that this JS file refers to where

Do not let us run the page, press F12 to see, it will automatically generate a JS file here, we simply refer to this path in the page

Four, the page effect (It's time to witness a miracle, hahaha ~ ~ ~)

In order to make the page effect more intuitive, I use IE to open sendmessage.cshtml page, with Google Open receivemessage.cshtml page.

Statement of responsibility

Sportsky Source: http://www.cnblogs.com/sportsky/
This article is copyright to the author and the blog Park, Welcome to reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to the original link, otherwise reserves the right to pursue legal responsibility. If you feel that there is help, you can click on the lower right corner of the "recommendation", hoping to continue to bring good technical articles for everyone! Want to make progress with me? Then "focus on" me.

SIGNALR implementing Message Push

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.