SIGNALR Introduction and Usage Introduction

Source: Internet
Author: User

This chapter and what we share is to use the signal R framework to create a simple group chat function, mainly to explain how to. NET MVC Use this framework, because this project has official documents (of course, all in English), there is no intention to write a share, the main purpose is to let friends in need to use web real-time communication, there is more a solution, after all, this is one of Microsoft's main push solution.

SIGNALR Online profile

The ASP. NET SignalR is a library for ASP. NET developers that simplifies the process of adding real-time WEB functionality to applications by developers. Real-time WEB functionality refers to the ability for server code to push content immediately when a connected client becomes available, rather than having the server wait for the client to request new data.

SIGNALR also offers a very simple and easy-to-use high-level API that allows the server side to invoke JavaScript functions on the client individually or in bulk, and makes it easy to manage connections, such as client connections to the server, or disconnection, client teaming, and client authorization. The use of SIGNALR is very easy to implement.

SIGNALR will communicate with the client in real-time to ASP. NET. Of course, this is useful, and there is enough extensibility. In the past, users need to refresh the page or use AJAX polling to achieve real-time display data, and now as long as the use of SIGNALR, it can be easily implemented. The most important thing is that you don't have to re-establish your project to use an existing ASP. NET project can be used seamlessly with SIGNALR.

Group Chat instance Effects

Let's take a look at the effect of the test case, here is the online effect link: God cow chat room (: 1001/home/shenniuchat),:

interface and its simple, style is not considered here, mainly to show its usage, here are the functions involved:

1. Statistics on number of people online

2. Display the nickname and connection method of the number of people online (this test case supports WebSockets and longpolling (long Connection))

3. Group chat Information

How to use SIGNALR in MVC

First, we usually practice creating MVC's Web project and then through the NuGet console command: install-package Microsoft.AspNet.SignalR joins the SignalR dependency, the packages are automatically added as follows:

  <package id= "Microsoft.AspNet.SignalR" version= "2.2.2" targetframework= "net45"/>  <package id= " Microsoft.AspNet.SignalR.Core "version=" 2.2.2 "targetframework=" net45 "/>  <package id=" Microsoft.AspNet.SignalR.JS "version=" 2.2.2 "targetframework=" net45 "/>  <package id=" Microsoft.AspNet.SignalR.SystemWeb "version=" 2.2.2 "targetframework=" Net45 "/>

and automatically add the relevant JS file to the script folder in the MVC project:

Jquery.signalr-2.2.2.min.jsjquery.signalr-2.2.2.js

Then we need to create a class with a file name called Startup.cs in the project-level directory, where the main content is incomplete:

1 [Assembly:owinstartup (typeof (Stage.Api.Extend.Startup))] 2 namespace Stage.Api.Extend 3 {4 Public     class Startup 5     {6 Public         void Configuration (Iappbuilder app) 7         {8             app. MAPSIGNALR ("/chat", new Microsoft.AspNet.SignalR.HubConfiguration 9             {ten                 enabledetailederrors = true,11                 Enablejavascriptproxies = True12             });         }14     }15}

First, we analyze the points from the top down:

1. The owinstartup (type) constructor passes a type, and this type corresponds to the startup class that we created, which marks the starting position by this constructor class;

2. namespace Stage.Api.Extend is the namespace of my project, which can be defined casually;

3. The public void Configuration (iappbuilder app) function is a fixed necessity, where the program will first enter the logic code inside the method execution;

4. app. MAPSIGNALR is an extended Iappbuilder interface method, he has a variety of representations, here I choose the public static Iappbuilder mapsignalr ( This Iappbuilder Builder, string path, hubconfiguration configuration); , here is a bit similar to the MVC route, here is the main note is the path parameter, in the front page of the time needed to use this route;

Back to the background needs of the configuration has been completed, the following is the specific need to operate the business logic processing Class , create a new class (here I named Chathub) and inherit the Hub(which is provided by the SIGNALR framework), Then the logic inside the code is as follows:

 1 public class Chathub:hub 2 {3//4 public int Num = 10001; 5 public static List<mohub user> _users = new list<mohubuser> (); 6 7//<summary> 8//Add chat 9//</summary>10//<param name= "user" ; </param>11 public void AddUser (Mohubuser user) Id = context.connectionid;15 if (!_users.any (b = = b.ID = = user.             ID) (_users.add) (user),}19//clients.all.newuser (user), 21 Clients.All.userList (_users);}23//<summary>25///Send information///&LT ;/summary>27//<param name= "user" ></param>28//<param name= "message" &GT;&LT;/PARAM&G t;29 public void Sendall (mohubuser user, String message)-{Clients.All.addNewMessageToPage (user, message); 32}33 34///&LT;SUMMARY&GT;35///A chat person quits Yes, notifies all online people to reload the chat number.//</summary>37//<param name= "stopcal  LED "></param>38//<returns></returns>39 public override System.Threading.Tasks.Task ondisconnected (bool stopcalled) + {$ var user = _users.singleordefault (x = x.id = = Context.conne Ctionid); if (user! = null) _users.remove (user); clients . All.userlist (_users);}47 return base. Ondisconnected (stopcalled); 48}49}

The above 3 methods do: Add the chat to list, send information to the client, a connection fails to notify the effective chat to reload the information; it is worth paying attention to the re-public override The System.Threading.Tasks.Task ondisconnected (bool stopcalled) method implements the capture and removal of the failed connection (here is the message of the chat); The entire test case passes Context.connectionid to ensure the uniqueness of the connection, as long as there is a new link request, then the server will assign a unique string to the link, When the client closes the page or closes the link this is the ConnectionID that can capture the failed link in the Ondisconnected method, so that the request to remove the failed chat is reached; for the convenience of the code, a chat person information class is created:

1 public  class MoHubUser2     {3 4 public         string Id {get; set;} 5 Public         string Nickname {get; set;} 6 Public         string Transportmethod {get; set;} 7     }

The chat room code in the background is so simple, so let's look at how to write the code, and here I'll give my HTML layout code:

 1 @{2 viewbag.title = "God cow chat room-SignalR"; 3} 4 <style type= "Text/css" > 5. div_left {6 width:70%; 7 Float:left; 8} 9 Div_right {width:28%;12 float:left;13}14. UL {List-style:no     ne;17 border:1px solid #ccc; height:500px;19 overflow-y: Scroll;20 color:black;21 }22 ul li {padding-top:5px;25 padding-right:25px;26}27. Ul_user {list-style:none;30}31. ul_user li {padding-top:5px;34}35. Sen d {PNS position:relative;38 background: #eae7e7; border-radius:5px;/* Fillet */40 padding- top:4px;41 padding-left:5px;42 margin-top:13px;43}44. Send. Arrow {posit ion:absolute;47 Top: -16px;48 font-size:0;49 border:solid 8px;50 border-color: #fff #fff #eae7e7 #fff,}52 </style>53 

The client here basically has two choices, a direct use of the generated proxy to operate, a proxy not automatically generated by the way to create a proxy, for the brevity of the content, here is only a simple explanation of the auto-generated proxy mode, and more is to share the way to manually create proxy links;

Get a link using the generated proxy

First, we need to use the script tag to refer to the path of the auto-generated proxy: <script src="~/chat/hubs"></script> , note that the path here /chat corresponds to the Startup.cs in front of the file to configure the app. MAPSIGNALR ("/chat" path, and the back /hubs fixed notation (at least for now I have not tried more), only the first application of this ~/chat/hubs In order to use the generated proxy later, the first segment of the code:

 1 var chat = $.connection.chathub; 2 Chat.client.newUser = function (user) {3 $ ("#users"). Append (' <li><strong> ' + user. Nickname + ' [' + user. Transportmethod + ']</strong></li> '); 4}; 5 6 chat.client.userList = function (users) {7 console.log (users); 8 $ ("#sapnUserTotal") . html (users.length); 9 $.each (Users, function (I, item) {Ten $ ("#users"). Append (' <li>[' + item. Transportmethod + '] <strong> ' + item. Nickname + ' </strong> (' + Item. Id + ') </li> ');};13 chat.client.addNewMessageToPage = function (user, message) {console.log (user); $ ("#discussion"). Append (' <li ><span><strong> ' + USER.N Ickname + ' [' + user. Transportmethod + ']</strong>:</span><div class= ' send ' > ' + message + ' <div class= ' arrow ' ></ Div></div></li> '); 16};//connection.hub.start ({transport: [' webSockets ', ' longpolling ']}). Done (function () {//My. Transportmethod = connection.hub.transport.name;19//Chat.server.addUser (my); $//$ (' #sendmessa GE '). Click (function () {/////console.log (chat);//var content = $.trim ($ (' #message '). V Al ()); (content.length <= 0) {$ (' #message '). Val ("). focus (); return;}    +//Chat.server.sendAll (my, content); +//$ (' #message '). Val ("). focus (); 27// }). Fail (function () {//alert ("The link chat room failed, please refresh the page again.") "); 30//});

Let's step through the code to note the point:

1. var chat = $.connection.chathub; Here the chathub corresponds to what we created and inherit the hub Chathub class, because the JS variable starts with lowercase, so this is Chathub , this is the link to the back end of the Chathub class, and then you can use the inside of the method (this is somewhat similar to the early webform of some kind of Ajax request writing)

2. Through the chat.client.xxx to receive the service-side notification message, and this xxx corresponding method name and the back end of the Clients.All.xxx, the example of this chapter corresponds to: Chat.client.userList = function (Users {} corresponds to Clients.All.userList (_users), so that the backend can directly notify the client of the corresponding method; note here my backend clients.all with the meaning of notifying all clients, if you need to notify the specified link need to use: T Client (string connectionid); Method

3. Chat.client is the backend call client, that the relative chat.server is the client request server, and the same as above through the chat.server.xxx to specify the requested service-side method, note that this time the service-side method refers to inheriting the class hub subclass of the public method (this article corresponds to: Chat . Server.sendall (My, content) corresponds to the public void Sendall in the ChatHub.cs file (mohubuser user, string message) function)

4. Connection.hub.start ({transport: ['webSockets', 'longpolling '] }) to specify the interactive protocol to run

The above is the use of the method of generating agents, according to the above note to write should not be a problem;

Use the manual create reverse proxy to link

Not using the generated code, we just need to modify the front-end of the line, the background code does not change or set no change; First we remove the code of the script referred to as the automatic proxy, because this time no need, Let's start with the code:

 1 var my = {nickname: "God Ox 001", Transportmethod: "}; 2 var connection = $.hubconnection ("/chat/hubs"); 3 var chat = connection.createhubproxy (' Chathub '); 4 5 Chat.on ("UserList", function (users) {6 console.log (users); 7 $ ("#sapnUserTotal"). HT ML (users.length); 8 $ ("#users"). HTML (""); 9 $.each (Users, function (I, item) {Ten $ ("#users"). Append (' <li>[' + item. Transportmethod + '] <strong> ' + item. Nickname + ' </strong> (' + Item.  Id + ') </li> '); Chat.on ("Addnewmessagetopage", function (user, message) {console.log (user), $ ("#discussion"). Append (' <li ><span><strong> ' + user. Nickname + ' [' + user. Transportmethod + ']</strong>:</span><div class= ' send ' > ' + message + ' <div class= ' arrow ' ></ Div></div></li> '); var div = Document.getelemeNtbyid (' discussion ');//div.scrolltop = div.scrollheight;20 div.scrolltop = 999999;21}) ; var nickname = prompt ("Please enter a nickname:", My.) Nickname), My. Nickname = nickname.length > 0? Nickname:my. Nickname;25 $ (' #displayname '). Val (nickname); $ (' #message '). focus (); Connection.star T ({transport: [' webSockets ', ' longpolling ']}). Done (function () {. Transportmethod = Connection.transport.name;32//console.log (My.                 Transportmethod) Chat.invoke ("AddUser", my); $ (' #sendmessage '). Click (function () {36 var content = $.trim ($ (' #message '). Val ()), PNS if (content.length <= 0) {$ (' #message '). Val (" ). focus (); Return             }38 Chat.invoke ("Sendall", my, content); $ (' #message '). Val ("). focus (); 41 }); 42});

Also list the following points of caution:

1. var connection = $.hubconnection ("/chat/hubs"); Create a link, where the path also corresponds to the backend app. MAPSIGNALR ("/chat" , the path remains the same

2. var chat = connection.createhubproxy ('chathub'); to create a reverse proxy link, The Name:chathub here corresponds to the Chathub class name at the back end.

3. Through the On ("XXX", function () {}) functions to bind the server to notify the client of the event, xxx corresponds to Clients.All.xxx in XXX

4. Connection.start ({transport: ['webSockets', 'longpolling' ]}) to set the allowed link and start the link

5. Connection.transport.name to get the method name of the link, the default start does not set the words there are several: websockets,foreverframe,serversentevents,longpolling

6. Chat.invoke ("xxx", param1, param2) uses invoke to map the public method of the class that inherits the class hub, where the instance corresponds to the following: Chat.invoke ("sendall ", my, content) corresponds to public void sendall (mohubuser user, string message)

Written in the last

If you meet the above points of attention, then the basic signalr can be linked to the use of success, more attention is more than the experience is summed up, I hope that many friends are helpful; when I wrote this article, just a friend was looking at my git open source lovepicture.web Project, It is said that they will also start to try to use Netcore in the company to build applications, I feel honored and happy, honored to take my project as an example, happy is netcore also more and more influential haha; If you feel this article can also, or give you harvest, may wish to point a recommendation , thank you!!!

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.