asp.net mvc use SIGNALR to implement push function _ practical skills

Source: Internet
Author: User
Tags dot net iis min visibility serverhub

First, Introduction

Signal is a Microsoft-supported HTML WebSocket framework that runs on the Dot NET platform. Its main purpose is to implement the server's proactive (push) message to the client page so that the client does not have to resend the request or use polling technology to get the message.
Access to its official website: https://github.com/SignalR/for more information.

Second, ASP.net signalr is a what Dongdong

ASP.net signalr is a class library for real-time communication in Microsoft. In general, SIGNALR uses a long, JavaScript-polling to communicate between the client and the server, and SIGNALR supports websockets communication as websockets occurs in HTML5. In addition, the program developed by SIGNALR not only restricts hosting in IIS, but also hosts any applications, including consoles, client programs and Windows services, and also supports mono, which means it can be deployed across platforms in a Linux environment.

There are two types of objects inside the SIGNALR:

HTTP Persistent connection (Persisten Connection) object: A feature used to troubleshoot a long time connection. It is also possible for the client to proactively request data from the server, and the server side does not need to implement much detail, only to handle the five events provided in Persistentconnection: onconnected, onreconnected, onreceived, OnError and OnDisconnect can be.
Hub (Hub) object: Used to solve the real-time (realtime) information exchange function, the server can use the URL to register one or more hubs, as long as the connection to the hub, can be shared with all the client to send information to the servers, while the service side can invoke the client script.
SIGNALR encapsulates the entire exchange of information, and both clients and servers use JSON to communicate, and all hub information declared at the server will generate JavaScript output to the client. NET relies on proxy to generate the proxy object, while the inside of the proxy converts JSON to an object.
Since SIGNALR is born for real time, it determines the place of use. The specific scenario has the following points:
Chat room, such as online customer service system, IM system, etc.
Real-time update of stock price
Push Service for messages
Real-time push of character position in game
At present, my company is developing an online customer service system.

III. Implementation Mechanism

The implementation mechanism of SIGNALR is similar to. NET WCF or Remoting and is implemented using remote proxies. In specific use, there are two different purposes of the interface: Persistentconnection and Hubs, where Persistentconnection is implemented for a long time Javascript polling (similar to the Comet), Hub is used to solve real-time information exchange problems, it is implemented using Javascript dynamic loading execution method. SIGNALR the entire connection, the information exchange process is very beautiful, the client and server side all use JSON to exchange data.

The following is the whole 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 at the client side;
3. Establish a connection between client and server (connection);
4. The client can then invoke the method of the proxy object to invoke the server-side method, which is to send the request to the server side;
5. After the server has received the request, it can send messages to a/group client or all clients (broadcasts).

Iv. using ASP.net signalr to implement broadcast messages on the web side

Through the second part of the introduction, I believe that we have a preliminary understanding of ASP.net signalr, and then through two examples to let everyone deepen the understanding of the SIGNALR operating mechanism. The first example is how to use SIGNALR to implement broadcast messages on the Web side.
Using Visual Studio 2013, create an MVC project
Install the SIGNALR package via NuGet. Right-key reference-"Select Management NuGet Package-" Enter SIGNALR in the window that appears to locate the SIGNALR package for installation.
After the installation signalr is successful, the SIGNALR library script will be added to the Scripts folder. As shown in the following illustration:

Add a SIGNALR Hub (v2) to your project and name it Serverhub.

Populate the Serverhub class you just created with the following code.

Using System;

Using Microsoft.AspNet.SignalR;  Namespace Signaldemo {public class Serverhub:hub {private static readonly char[] Constant = {' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' g ', ' h ', ' I ', ' j ', ' K ', ' l ', ' m ', ' n ', ' o ', ' P ', ' Q ', ' R ', ' s ', ' t ', ' u ', ' V ', ' w ', ' x ', ' y ', ' z ', ' A ', ' B ', ' C ', ' D ', ' E ', ' F ', ' G ', ' H ', ' I ', ' J ', ' K ', ' L ', ' M ', ' N ', ' O ', ' P ',

 ' Q ', ' R ', ' S ', ' T ', ' U ', ' V ', ' W ', ' X ', ' Y ', ' Z '}; <summary>///server-side code for client invocation///</summary>///<param name= ' message ' ></param> public void

 Send (String message) {var name = Generaterandomname (4);
 Invokes the SendMessage method Clients.All.sendMessage (name, message) for all clients; ///<summary>///generates random user name functions///</summary>///<param name= "Length" > Username length </param>///< returns></returns> public static string generaterandomname (int length) {var newrandom = new System.Text.Strin
 Gbuilder (62); var rd = new Random (); for (var i = 0; i < length; i++) {newrandom.append (CONSTANT[RD).
 Next (62)]);
 return newrandom.tostring ();
 }
 }
}

Create a startup class that is added by default if you start to create an MVC project without changing the authentication, if you do not need to add it again. Update the startup class with the following code.

Using Microsoft.owin;
Using Owin;

[Assembly:owinstartupattribute (typeof (Signaldemo.startup))]
Namespace Signaldemo
{public
 partial class Startup
 {
 #region myregion public
 void Configuration ( Iappbuilder app)
 {
 app. MAPSIGNALR ();
 Configureauth (app); 
 #endregion
 }
}

Create a chat action method in the home controller

Using SYSTEM.WEB.MVC;

Namespace Signaldemo.controllers
{public
 class Homecontroller:controller
 {
 public ActionResult Chat ()
 {return
 View ();
 }
 }
}

Create a chat view in the home folder in the views file, as shown in the View code:

@{viewbag.title = "Chat";}  

Modify the Routconfig class in the App_start folder and set the action method by default to chat

Using SYSTEM.WEB.MVC;
Using System.Web.Routing;

Namespace Signaldemo
{public
 class Routeconfig
 {public
 static void RegisterRoutes (RouteCollection Routes)
 {
 routes. Ignoreroute ("{resource}.axd/{*pathinfo}");
 Routes. Maproute (
 name: "Default",
 URL: "{controller}/{action}/{id}",
 defaults:new {controller = "Home", Action = "Chat", id = urlparameter.optional}
 );}}


So, our example is done, so let's take a look at how it works, and then explain exactly how SIGNALR is going to complete the broadcast message. The running results are as follows.

From the run results, you can find that in any one of the Windows input information and send, all clients will receive the message. Such effects in the actual application of a lot, such as QQ, a login QQ will push Tencent advertising message.

After reading the results of the operation, we will analyze the next code, and then to analyze the SIGNALR in the end is how to work.

According to B/S mode, when running the program, the Web page is connected with the SIGNALR service, the specific code to establish the connection is:$.connection.hub.start (). The function of this code is to establish a connection with the SIGNALR service, followed by the done function to indicate that after the successful connection to the Send button registered a click event, when the client input click the Send button, the Click event will trigger, triggering the action to do is: Chat.server.send ($ (' #message '). Val ()). This code indicates that the Send function is invoked on the service side, and the send Korean on the server is the SendMessage function that invokes all clients, and the SendMessage function in the client is to add the information to the corresponding message list. This realizes the function of broadcasting the message.

See here, whether someone will have questions, the previous implementation has only used the hub object, but not the persistent connection object. In fact, this is not the case, $.connection this code is to use persistent connection objects, of course, you can also onconnected methods to view the monitoring of the client connection, the updated code as follows:

public class Serverhub:hub {private static readonly char[] Constant = {' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ' ', ' 9 ', ' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' g ', ' h ', ' I ', ' j ', ' K ', ' l ', ' m ', ' n ', ' o ', ' P ', ' Q ', ' R ', ' s ', ' t ', ' u ', ' V ', ' W ', ' x ', ' y ', ' z ', ' A ', ' B ', ' C ', ' D ', ' E ', ' F ', ' G ', ' H ', ' I ', ' J ', ' K ', ' L ', ' M ', ' N ', ' O ', ' P ', ' Q ', ' R ', ' S ', ' T ', ' U '

 , ' V ', ' W ', ' X ', ' Y ', ' Z '}; <summary>///server-side code for client invocation///</summary>///<param name= ' message ' ></param> public void

 Send (String message) {var name = Generaterandomname (4);
 Invokes the SendMessage method Clients.All.sendMessage (name, message) for all clients; ///<summary>///Client connection call///</summary>///<returns></returns> public override Task O
 Nconnected () {trace.writeline ("Client connection succeeded"); Return base.
 Onconnected (); ///<summary>///generates random user name functions///</summary>///<param name= "Length" > Username length </param>///< Returns></returns> PublIC static string generaterandomname (int length) {var newrandom = new System.Text.StringBuilder (62);
 var rd = new Random (); for (var i = 0; i < length; i++) {newrandom.append (CONSTANT[RD).
 Next (62)]);
 return newrandom.tostring (); 
 }
 }

This way, when you run the page, you will see the word "Client connection succeeds" in the Output window. The effect is as shown in the following illustration:

In the second part of the introduction of the time, said in the server-side declaration of all hub information, will generate JavaScript output to the client, in order to verify this, you can F12 in chrome to see the source code is clear, as shown in the following figure:

See above, you also understand why the chat.cshtml page needs to introduce the "signalr/hubs" script library.

<!--reference SIGNALR library. -->
<script src= "~/scripts/jquery.signalr-2.2.0.min.js" ></script>
<!--reference SIGNALR hub (hub) scripts that are automatically generated. When running, you can see--> in the browser's source.
<script src= "~/signalr/hubs" ></script>

V. How to use asp.net signalr in desktop programs

The above section describes the implementation of SIGNALR in ASP.net MVC, which will take an example to see how signalr is used in WPF or WinForm. In fact, this part of the implementation is very similar to ASP.net mvc, the main difference is that asp.net mvc in the SIGNALR server hosted in IIS, and in WPF application, we put SIGNALR hosted in the WPF client.

Now let's look at the implementation of the SIGNALR server.

<summary>///launches SIGNALR service to host SIGNALR service in WPF program///</summary> private void StartServer () {try {Si GNALR = Webapp.start (Serveruri);
 Start SIGNALR Service} catch (TargetInvocationException) {writetoconsole ("a service already running in:" + Serveruri); Dispatcher callback to set UI control state this.
 Dispatcher.invoke (() => buttonstart.isenabled = true);
 Return } this.
 Dispatcher.invoke (() => buttonstop.isenabled = true);
 Writetoconsole ("Service has been successfully launched, the address is:" + Serveruri); 
 public class Chathub:hub {public void Send (string name, String message) {Clients.All.addMessage (name, message); public override Task onconnected () {//Application.Current.Dispatcher.Invoke (() => (MainWindow) application. Current.mainwindow).

 Writetoconsole ("Client connection, connection ID is:" + Context.connectionid)); Return base.
 Onconnected (); public override Task ondisconnected (bool stopcalled) {Application.Current.Dispatcher.Invoke (() => (MainWindow) Application.Current.MainWindow). Writetoconsole ("Client disconnected, connection IDis: "+ Context.connectionid)"; Return base.
 Ondisconnected (TRUE); } public class Startup {public void Configuration (Iappbuilder app) {////For more information about how to configure the application, visit Http://go.microsoft. com/fwlink/? linkid=316888//allows cors//app across domains.
 Usecors (Corsoptions.allowall); App.
 MAPSIGNALR ();
 }
 }

Through the above code, we signalr the implementation of the service end, and its implementation logic is similar to asp.net MVC code.

Next, let's look at how the WPF client connects and communicates with the server. The implementation of the specific client is as follows:

Public Ihubproxy Hubproxy {get; set;}
 Const string Serveruri = "HTTP://LOCALHOST:8888/SIGNALR";

 Public hubconnection Connection {get; set;}

 Public MainWindow () {InitializeComponent ();
 Start the Connection service ConnectAsync () when the window starts; ///<summary>///Send message///</summary>///<param name= "sender" ></param>///<param Name = "E" ></param> private void Buttonsend_click (object sender, RoutedEventArgs e) {//server-side Send method via proxy//server-side SE

 The ND method then invokes the client's AddMessage method to output the message to the message box Hubproxy.invoke ("Send", Generaterandomname (4), TextBoxMessage.Text.Trim ());
 Textboxmessage.text = String.Empty;
 Textboxmessage.focus ();
 Private async void ConnectAsync () {Connection = new hubconnection (Serveruri);

 connection.closed + = connection_closed;

 Create a hub proxy object hubproxy = Connection.createhubproxy ("Chathub"); For service-side invocation, output messages to the message list box hubproxy.on<string, string> ("AddMessage", (name, message) => this. Dispatcher.invoke (() => Richtextboxconsole.appendteXT (String.Format ("{0}: {1}\r", name, message)));
 try {await connection.start ();
 The catch (httprequestexception) {//connection failed return;
 }//Show chat control chatpanel.visibility = visibility.visible;
 Buttonsend.isenabled = true;
 Textboxmessage.focus ();
 Richtextboxconsole.appendtext ("Connected service:" + Serveruri + "\ r");
 }

The code above is the core code implemented by the WPF client, and the main logic is that the client invokes the Connection.start method to connect to the server when it is started. The Send method in the hub is then invoked through the Hubproxy proxy class, and the Send method in the hub completes the push process of the message by calling the client's AddMessage method to display the message to the client's message box. Next, let's look at how it works:

From the above operation effect to see, its effect and asp.net mvc effect is the same.

Summarize

Here, all the content of this topic is over, this article Signalr quick Introduction is also I in the learning SIGNALR process some experience, hope can help some just contact signalr friend Quick Start. This article mainly realizes the SIGNALR broadcast message function, may realize the handset side message push the function, next one will explain how uses the signalr to realize one-to-one chats.

SOURCE Download: Http://xiazai.jb51.net/201609/yuanma/ASP.NETSignalDemo.rar

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.