asp.net signalr Quick Start _ Practical Tips

Source: Internet
Author: User
Tags visibility serverhub

Today's topic is to enable you to quickly start ASP.net signalr. No more nonsense, the following formally entered the content of today's topic.

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.

The specific interaction between client and server is shown in the following illustration:

From the above introduction can be seen, signalr since is born for real-time, so that determines the use of the site. The specific scenario has the following points:

1, chat room, such as online customer service system, IM system, etc.
2. Real-time update of stock price
3, the message of the push service
4. Real-time push of character position in game
At present, my company is developing an online customer service system.

Iii. 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:


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

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

Using Microsoft.AspNet.SignalR;
Using Microsoft.AspNet.SignalR.Hubs;

Using System; Namespace Signalrquickstart {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 &LT;/PARAM&G
    T
  <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 ();

 }
  }
}

6. Create a startup class that will be 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.

7. Create a home action method in the home controller

public class Homecontroller:controller
  {public
    actionresult Index ()
    {return
      View ()
    }

    Public ActionResult About ()
    {
      viewbag.message = "Your Application description page."

      return View ();
    }

    Public ActionResult Contacts ()
    {
      viewbag.message = "Your contact page."

      return View ();
    }

    Public ActionResult Chat ()
    {return
      View ();
    }
  }

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

@{viewbag.title = "Chat window";}  

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

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 onconnected () {trace.writeline ("Client connection succeeded"); Return base.
    Onconnected (); ///<summary>///generates random user name functions/// </summary>///<param name= "Length" > Username length </param>///<returns></returns> publi
      C 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>
   <!--references automatically generated SIGNALR Hub (hub) script. At run time, you can see-->
  <script src= "~/signalr/hubs" under the browser source ></script>

Iv. 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>///starts the SIGNALR service to host the SIGNALR service in the WPF program///</summary> private void StartServer () { try {signalr = Webapp.start (Serveruri);//start SIGNALR service} catch (Targetinvocationexceptio
        N) {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 (nam
    e, message); public override Task onconnected () {//Application.Current.Dispatcher.Invoke (() => () (Ma Inwindow) 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.MainWin Dow).

      Writetoconsole ("Client disconnected, connection ID is:" + Context.connectionid)); Return base.
    Ondisconnected (TRUE); } public class Startup {public void Configuration (Iappbuilder app) {///For more information about how to configure the application, visit the 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 messages///</summary>///<param name= "Sender" ></param>/// <param name= "E" ></param> private void Buttonsend_click (object sender, RoutedEventArgs e) {//Pass The proxy to invoke the server-side Send method//service-side Send method then invokes the client's AddMessage method to output the message to the message box Hubproxy.invoke ("Send", Generaterandomname (4), Text

      BoxMessage.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.

V. Summary
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.

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.