Use signalr in ASP. net mvc to implement the push function

Source: Internet
Author: User
Tags dot net actionlink
ArticleDirectory
    • I. Introduction
    • II. Implementation Mechanism
    • 3. Hub example tutorial
    • Iv. Example of persistent connection
Use signalr in ASP. net mvc to implement the push function

Luo chaohui (http://www.cnblogs.com/kesalin/)

CC license. For more information, see Source   I. Introduction

Signal is an HTML websocket framework supported by Microsoft running on the dot NET platform. The main purpose of this function is to enable the server to actively push messages to the client page, so that the client does not have to resend requests or use polling technology to obtain messages.

Visit its official website: https://github.com/SignalR/ for more information.

 

II. Implementation Mechanism

The implementation mechanism of signalr is similar to that of. Net WCF or remoting. It is implemented using remote proxy. There are two interfaces for different purposes:PersistentconnectionAndHubsPersistentconnection implements long-time JavaScript round robin (similar to comet). Hub is used to solve the problem of real-time information exchange. It is implemented by using JavaScript dynamic loading and execution methods. Signalr encapsulates the entire connection and the information exchange process is very beautiful. the client and the server use JSON to exchange data.

 

The following describes the entire process of using the hubs interface:

1. Define the corresponding hub class on the server side;

2. Define the proxy class corresponding to the Hub class on the client;

3. establish a connection between the client and the server );

4. Then the client can call the proxy object method to call the server method, that is, send the request to the server;

5. After receiving the request, the server can send messages to A/group client or all clients (broadcast.

 

3. Hub Example 1. Tool preparation

Signalr runs on the. NET 4.5 platform, so you need to install. Net 4.5. For ease of demonstration, ASP. net mvc is used in this example in win 7 system. Install ASP. net mvc 3 or ASP. net mvc 4.

 

2. Build a project

Open the ASP. Net MVC 3 web application project named signalrtutorial created in vs2010/vs2012, select the Internet application template, Razor view engine, and select the use HTML 5 tab.

3. Install signalr

Open the nuget Package Manager Console (tools-> library Package Manager), enter install-package signalr. sample, and press enter to install the package. :

4. Implement the hub server Code

Create a new signalr directory in the project and add the chathub. CS file as follows:

NamespaceSignaltutorial. signalr {[hubname ("Chat")]Public ClassChat: hub {Public VoidSend (StringClientname,StringMessage ){//VaR toselfinfo = "you had sent message" + message;//Caller. addsomemessage (clientname, toselfinfo );//Call the addmessage Method on all clientsClients. addsomemessage (clientname, message );//Clients [context. connectionid]. addsomemessage (clientname, data );}}}

In the above Code:

1) hubname is used to let the client know how to create a proxy object for the service corresponding to the server. If this attribute is not set, the service class name on the server is used as the default value of hubname;

2) chat is inherited from the hub. The following hub interface diagram shows that the hub supports the request initiator (caller), all clients (clients), and specific groups) push messages.

 

3), Public void send (string clientname, string message) is called by the client through the proxy object;

4) clients is the property of hub, indicating the client pages of all links. It is dynamic like caller, because it must correspond directly to JavaScript objects;

5), clients. addsomemessage (clientname, message); indicates that the server calls the addsomemessage method of the client. This is a JavaScript method to push messages to the client.

6). Conclusion: The service implemented here is very simple. After a client calls the send method to send a message to the server, the server is responsible for broadcasting the message to all clients (you can also broadcast the message to a specific group or client, see the blocked Code) to implement the functions of the chat room.

 

5. Implement the hub client code 1) and reference signalr Javascript

To simplify the operation of referencing the signalr script, I directly introduced signalr and other scripts in view/shared/_ layout. cshtml:

 <  Head  >          <  Meta  Charset  = "UTF-8"   />          <  Title > @ Viewbag. Title </  Title  >          <  Link  Href  = "@ URL. Content ("  ~ /Content/site.css ")" rel  = "Stylesheet"  Type  = "Text/CSS"   />          <  Script  SRC  = "@ URL. Content ("  ~ /Scripts/jquery-1.5.1.min.js ")" Type  = "Text/JavaScript"  > </  Script  >          <  Script  SRC  = "@ URL. Content (" ~ /Scripts/jquery-1.6.4.js ")" Type  = "Text/JavaScript"  > </  Script  >          <  Script  SRC  = "@ URL. Content ("  ~ /Scripts/jquery-ui-1.8.24.js ")" Type  = "Text/JavaScript"  > </  Script  >          <  Script  SRC  = "@ URL. Content ("  ~ /Scripts/jquery. signalR-0.5.3.js ")" Type  = "Text/JavaScript"  > </  Script  >          <  Script SRC  = "@ URL. Content ("  ~ /Scripts/modernizr-1.7.min.js ")" Type  = "Text/JavaScript"  > </  Script  >          <  Script  SRC  = "@ URL. Content ("  ~ /Signalr/hubs ")" Type  = "Text/JavaScript"  > </  Script  >      </  Head  > 

Note: signalr depends on jquery, so signalr must be placed after jquery, while hubs must be placed after signalr.

Then add the hubchat tab to the body:

<Li>@ Html. actionlink ("hubchat", "hubchat", "home ")</Li>

 

2) generate an access page

Add the following method to homecontroller:

 
PublicActionresult hubchat () {viewbag. clientname ="User-"+ RND. Next (10000,99999);ReturnView ();}

Here, the server sets the client name based on the random number, which is not rigorous enough, because the name generated by the random number is not unique. Here, it is only a simplified demonstration, and the guid should be used in practical applications.

Then generate the corresponding view: hubchat. cshtml

@ Model Dynamic @ {viewbag. Title = "title ";} <  Script  SRC  = "@ URL. Content ("  ~ /Scripts/hubdemo. js ")" Type  = "Text/JavaScript"  > </  Script >  <  Script  Type  = "Text/JavaScript"  > $ (Document). Ready ( Function (){}); </  Script  >  <  H2  > Hub chat </  H2  >  <  Div  >      <  Input  Type  = "Text"  ID  = "Placeholder"  Value  = "@ Viewbag. clientname" Hidden  = "True"  />      <  Input  Type  = "Text"  ID  = "MSG"   />      <  Input  Type  = "Button"  ID  = "Broadcast"  Value  = "Broadcast"   />          <  BR  />      <  BR  />      <  H3  > Message record: (You are: < Span  ID  = "Myclientname"  > @ Viewbag. clientname </  Span  > ): </  H3  >      <  Ul  ID  = "Messages"  >      </  Ul  >  </  Div  > 

In the code on the above page, I added the hubdemo name. JS script, which will be introduced below; there is also a hidden input control with ID placeholder to pass the client name to JavaScript.

 

3) Compile Javascript

Add a new javescript to the scripts directory: hubdemo. js. The content is as follows:

$ (Function (){ VaR Myclientname = $ ('# placeholder'). Val (); //  Proxy created on the fly      VaR Chat = $. Connection. Chat; //  Declare a function on the chat hub so the server can invoke it Chat. addsomemessage = Function (Clientname, message) {writeevent ('<B>' + clientname + '</B>:' + message, 'event-message ');}; $ ("# broadcast "). click ( Function (){ //  Call the chat method on the server Chat. Send (myclientname, $ ('# MSG'). Val (). Done ( Function () {Console. Log ('sent message success! ');}). Fail ( Function (E) {console. Warn (e );});}); //  Start the connection $. Connection. Hub. Start (); //  A function to write events to the page      Function Writeevent (Eventlog, logclass ){ VaR Now = New Date (); VaR Nowstr = now. gethours () + ':' + now. getminutes () + ':' + now. getseconds (); $ ('# messages '). prepend ('<li class = "+ logclass +"> <B>' + nowstr + '</B>' + EventLog + '. </LI> ');}});

 

The code above has a detailed comment, and the key points are described below:

1. first obtain the name of the client page;

2. Then, use $. Connection. chat to create a proxy chat for the hub class on the server;

3. Define the client's JavaScript method addsomemessage. The server calls the client's method through dynamic to implement the push function. Every time you receive a message pushed by the server, you can insert the message in the messages list header on the client page.

4. When you click the broadcast button, the client uses the proxy object to call the send method of the server to send messages to the server.

5. Open the link through the $. Connection. Hub. Start (); statement.

 

6) Compile and run the hub example

Open the page in multiple browser windows. The effect is as follows:

 

Iv. Example of persistent connection 1. Implement server-side code 1) Compile server persistentconnection code

Add the persistentconnection. CS file to the signalr directory of the project. The content is as follows:

 Using System; Using System. Collections. Generic; Using System. Threading. tasks; Using Signalr;Namespace Signaltutorial. signalr { Public   Class Myconnection: persistentconnection { Protected   Override Task onconnectedasync (irequest request, String Connectionid ){ Return Connection. Broadcast ( "  Connection  " + Connectionid + "  Connected  " );} Protected   Override Task onreconnectedasync (irequest request, ienumerable < String > Groups, String Clientid ){ Return Connection. Broadcast ( "  Client  " + Clientid + "  Re-connected  " );} Protected   Override Task onreceivedasync (irequest request, String Connectionid, String Data ){ VaR Info = Data + "  . Connectionid is [  " + Connectionid + "  ]  " ; // Return connection. Send (connectionid, Info );  //  Broadcast Data to all clients              Return Connection. Broadcast (Info );} Protected   Override Task ondisconnectasync ( String Connectionid ){ Return Connection. Broadcast ( "  Connection  " + Connectionid + "  Disconncted  " );} Protected   Override Task onerrorasync (Exception error ){ Return Connection. Broadcast ( "  Error ocurred  " + Error );}}}

In the above Code:

1. myconnection is inherited from persistentconnection, so that we can process the connection in case of client connection, reconnection, disconnection, message sending, and connection error. The following persistentconnection interface shows that persistentconnection also supports group push.

2. Push messages are provided by the persistentconnection attribute connection, which inherits from the iconnection interface. This interface provides two functions to push and broadcast messages to specific clients.

System. Threading. Tasks. Task send (string signal, object value)
System. Threading. Tasks. Task broadcast (object value)

 

2) configure the access route

To support client access, you must configure it in the routing table. Open global. asax. CS and modify the application_start () function as follows:

Protected VoidApplication_start () {arearegistration. registerallareas (); routetable. routes. mapconnection <myconnection> ("Echo","Echo/{* operation}"); Registerglobalfilters (globalfilters. filters); registerroutes (routetable. routes );//Make connections wait 50 s maximum for any response. After//50 s are up, trigger a timeout command and make the client reconnect.Globalhost. configuration. connectiontimeout = timespan. fromseconds (50);//Disconnecttimeout//Heartbeatinterval//Keepalive}

In the above code, I map echo and its sub-path access to myconnection, and set the connection timeout to 50 s. You can also set other parameters, such as the disconnection timeout time and heartbeat interval.

 

2. implement client code 1) to generate access pages

Based on the previous three hub sample tutorials, we will add the persistent connection demonstration to this project. Add the persistentchat tab to _ layout. cshtml as before:

 
<Li>@ Html. actionlink ("persistentchat", "persistentchat", "home ")</Li>

Then add the following method to homecontroller:

 
PublicActionresult persistentchat () {viewbag. clientname ="User-"+ RND. Next (10000,99999);ReturnView ();}

Here, the server sets the client name based on the random number, which is not rigorous enough, because the name generated by the random number is not unique. Here, it is only a simplified demonstration, and the guid should be used in practical applications.

Then generate the corresponding page: persistentchat. cshtml:

@ Model Dynamic @ {viewbag. Title = "title ";} <  Script  SRC  = "@ URL. Content ("  ~ /Scripts/persistent. js ")" Type = "Text/JavaScript"  > </  Script  >  <  H2  > Persistent chat </  H2  >  <  Div  >      <  Input  Type  = "Text"  ID  = "Placeholder"  Value  = "@ Viewbag. clientname"  Hidden  = "True"  />      <  Input  Type  = "Text" ID  = "MSG"   />      <  Input  Type  = "Button"  ID  = "Broadcast"  Value  = "Broadcast"   />      <  BR  />      <  BR  />          <  H3  > Message record: (You are: <  Span  ID  = "Myclientname"  > @ Viewbag. clientname </  Span > ): </  H3  >      <  Ul  ID  = "Messages"  >      </  Ul  >  </  Div  > 

In the code on the above page, I added persistent. JS script, which will be introduced below; there is also a hidden input control with ID placeholder to pass the client name to JavaScript.

 

2) Compile Javascript

Add a new javescript: Persistent. js to the scripts directory. The content is as follows:

$ ( Function (){ VaR Myclientname = $ ('# placeholder'). Val ();VaRConnection = $. Connection ('/ECHO'  );      Connection. Received (  Function  (Data) { VaR MSG = New String (data ); VaR Index = msg. indexof ("#"); VaR Clientname = msg. substring (0, index ); VaR Content = msg. substring (index + 1 ); If (Clientname = Null | Clientname = "") {writeevent ('<B>' + "system message" + '</B>:' + content, 'event-message ');} Else {Writeevent ('<B>' + clientname + '</B>:' + content, 'event-message ');}}); Connection. Start (); $ ("# Broadcast"). Click ( Function (){ VaR MSG = myclientname + "#" + $ ('# MSG'). Val (); Connection. Send (MSG ); }); //  A function to write events to the page      Function Writeevent (Eventlog, logclass ){ VaR Now = New Date ();VaR Nowstr = now. gethours () + ':' + now. getminutes () + ':' + now. getseconds (); $ ('# messages '). prepend ('<li class = "+ logclass +"> <B>' + nowstr + '</B>' + EventLog + '. </LI> ');}});

The above code is basically the same as the previous Hub implementation and will not be described here. There are two points worth noting:

1. When creating a connection, specify the path "/echo". The route ing table on the server side is mapped to myconnection. Therefore, the connection is directed to the myconnection provided earlier.

2. Put the clientname information in the message, and use # To connect the clientname and message content into a MSG.

 

3. Compile and run the persistent example

 

V. References

Signalr: https://github.com/SignalR/

Use signalr to implement remote program control:

Http://blog.darkthread.net/post-2012-07-10-signalr-remote-controller.aspx

Example of a cool synchronization operation table (using jtable ):

Http://www.codeproject.com/Articles/315938/Real-time-Asynchronous-Web-Pages-using-jTable-Sign

Group notification example:

Http://www.codeproject.com/Articles/404662/SignalR-Group-Notifications

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.