Asp.net signalr makes real-time communication so easy

Time:2020-2-26

In the patrol project, you need to send real-time messages and start to remind tasks, so you have the opportunity to contact signalr. In the process of using, it is found that it is very simple to use signalr to realize communication. I think I will share it in three aspects:

1、 What is signalr

Asp.net signalr is a class library of Microsoft for real-time communication. In general, signalr uses long polling of JavaScript to realize communication between client and server. With the appearance of WebSockets in HTML5, signalr also supports WebSockets communication. In addition, the programs developed by signalr are not only limited to IIS, but also can be hosted in any application program, including console, client program, windows service, etc. in addition, it also supports mono, which means that it can be deployed in a linux environment across platforms.

There are two types of objects within signalr:

HTTP persistent connection object: function used to solve long-term connection. The client can also actively request data from the server, but the server does not need to implement too many details. It only needs to handle the five events provided in persistentconnection: onconnected, onreconnected, onreceived, onerror and ondisconnect.

Hub object: it is used to solve the function of real-time information exchange. The server can register one or more hubs by using the URL. As long as it is connected to the hub, it can share the information sent to the server with all clients. At the same time, the server can call the client’s script.

Signalr encapsulates the whole information exchange. Both the client and the server use JSON to communicate. All the hub information declared on the server will generate JavaScript output to the client. Net relies on proxy to generate proxy objects, while the internal proxy is to convert JSON to objects.

2、 Why use signalr

Chat rooms, such as online customer service system, IM system, etc

Real time push service of message

Real time push of patrol position

3、 How to realize signalr? The following is mainly about the first function of signalr, chat. Here is a simple demo:

1. Create a new asp.net web application

2. Select template MVC and change no authentication

3. Select the new project, right-click and choose manage nuget packages > search for signer > install Microsoft asp.net signer

4. New startup program startup.cs

Add code to the class:


app.MapSignalR();

5. New signalr hub class chathub.cs

6. Add the following code to the hub class chathub.cs

public class ChatHub : Hub
 {
  /// <summary>
  ///Server side code for client calls
  /// </summary>
  /// <param name="message"></param>
  public void Send(string message)
  {
   var name = Guid.NewGuid().ToString().ToUpper();
   //Call SendMessage method of all clients
   Clients.All.sendMessage(name, message);
  }

  /// <summary>
  ///Called when the client connects
  /// </summary>
  /// <returns></returns>
  public override Task OnConnected()
  {
   Trace.writeline ("client connection successful");
   return base.OnConnected();
  }
 }

7. Modify index.cshtml page code

@{
 Viewbag.title = "chat window";
}

<h2>Chat</h2>

<div>
 <input type="text" />
 <input type="button" value="Send" />
 <input type="hidden" />
 <ul></ul>
</div>

@section scripts
{
 <! -- reference signalr library. -- >
 <script src="~/Scripts/jquery.signalR-2.2.2.min.js"></script>
 <! -- reference the automatically generated signalr hub script. You can see it under the browser's source when running -- >
 <script src="~/signalr/hubs"></script>

 <script>
  $(function () {
   //1. Reference to the automatically generated hub agent must start with a lowercase letter
   var chat = $.connection.chatHub;

   //2. Start to connect to the server. The done function indicates that a click event is registered for the send button after the connection is successfully established
   $.connection.hub.start().done(function () {
    $('#sendmessage').click(function () {
     //The send method that calls the server-side hub also starts in lowercase
     chat.server.send($('#message').val());
     //Clear input box information and get focus
     $('#message').val('').focus();
    });
   });

   //3. Define the client SendMessage called by the server to display the new message
   chat.client.sendMessage = function (name, message) {
    //Add message to page
    $('#discussion').append('<li><strong>' + htmlEncode(name)
     + '</strong>: ' + htmlEncode(message) + '</li>');
   };

   //Set focus to input box
   $('#message').focus();
  });

  //HTML encoding for displayed messages
  function htmlEncode(value) {
   var encodedValue = $('<div />').text(value).html();
   return encodedValue;
  }
 </script>
}

8. Run the program directly, open multiple web pages, you can receive the same message.. As follows:

To sum up, signalr is easy to use, simple to configure and powerful.

The above asp.net signalr makes real-time communication so simple, which is all the content shared by the editor. I hope it can give you a reference, and I hope you can support developpaer more.