Application of ASP. NET SIGNALR and implementation of the group chat function example

Source: Internet
Author: User
Tags button type sendmsg
This article is mainly for you to share the ASP. NET SIGNALR application and implement group chat function, with certain reference value, interested in small partners can refer to

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. (from the official introduction.) )

SIGNALR official website

-1, the reason for writing this article

In the previous article b/s (WEB) real-time communication solutions, and no details introduced SIGNALR, so another one specifically introduced SIGNALR, the focus of this article is the hub function.

0, first look at the final realization effect

Github.com/emrys5/signalrgroupchatdemo

1. Preparatory work

1.1. First download the SIGNALR package on NuGet.

1.2, configuration Owin and SIGNALR

1.2.1, new startup class, Register SIGNALR

public class Startup {public void Configuration (Iappbuilder app) {  app. MAPSIGNALR (); } }

The startup class is then configured in Web. config and added in the Configuration=>appsettings node

<add key= "Owin:appstartup" value= "SignalRChat.App_Start.Startup"/>

1.2.2, the introduction of SIGNALR JS on the page

1, because the SIGNALR front-end is based on jquery, so the page needs to introduce jquery.

2, introduction of Signalr JS.

3, the introduction of the most important hubs JS, this JS actually does not exist, SIGNALR will be reflected to get all the methods for client calls into hubs JS.

<script src= "~/scripts/jquery-1.10.2.js" ></script><script src= "~/scripts/ Jquery.signalr-2.2.1.min.js "></script> <script src=" ~/signalr/hubs "></script>

1.2.3, new Groupchathub class, and inherit hub abstract class

The method in the Hub class is the JS method that is provided to the client for invocation.

In JS, you can call sendmsg with SIGNALR.

[Hubname ("Simplehub")] public class Simplehub:hub {public  void sendmsg (String msg) {}}

So basically the preparatory work is finished, the following is the specific operation.

2. Principle and simple programming

In fact, if the principle of simple understanding is very simple, because HTTP is stateless, so each request will be disconnected from the server, that is to say that the client can easily find the server, but the server if you want to send a message to your client is more troublesome, if you do not understand can refer to the previous article b/s (Web ) Real-time communication solutions.

SIGNALR is a good solution to this problem, also said that the implementation of the browser and the server to achieve full-duplex communication.

2.1. Client-to-server (B=>s)

Client code

<script type= "Text/javascript" >  var ticker = $.connection.simplehub; $.connection.hub.start (); $ ("#btn"). Click (function () {///link is complete, you can send a message to the server TICKER.SERVER.SENDMSG ("message to be sent");}); </script>

Service-side code

[Hubname ("Simplehub")] public class Simplehub:hub {public void sendmsg (String msg) {  //Get link ID  var connectionid = Context.connectionid;   Get cookie  var cookie = context.requestcookies;}}

Where Simplehub is our definition of inheriting the hub class Simplehub, then we can rename it with the feature hubname.

Then start the link.

After the link is complete, we can invoke the method called in the Simplehub class. This is a simple implementation of the client to the server to send messages.

We can also get what we want in the context, such as link id,cookie and so on.

2.2. Service-to-client (S=>B)

Service-side code

[Hubname ("Simplehub")] public class Simplehub:hub {public void sendmsg (String msg) {  Clients.All.msg ("message sent to client");  } }

Client code

<script type= "Text/javascript" > var ticker = $.connection.groupchathub; $.connection.hub.start (); Ticker.client.msg = function (data) {Console.log (data);} </script>

Here is a demonstration of how to send the message to the client, but also signalr more important features, there are two issues to be resolved.

Problem one, here is to send a message to all attached clients, if it is a single client or a batch of clients should be how to send.

Second, we call MSG to send a message to a client is the feedback after receiving the message, and then send a message to the client, which is similar to Ajax, the server does not actively send a message to the client.

Solve:

Problem one, clients can send messages to a group of attributes or to a client

All people Clients.All.msg ("messages sent to the client"); Specific cooectionidclients.client ("ConnectionID"). MSG ("message sent to Client");//Specific Groupclients.group ("GroupName"). MSG (" Messages sent to the client ");

This is a more commonly used three, of course, there are many, such as allexcept,clients.

In the SignalR2.0 also added others,othersingroup,othersingroups and so on.

Problem two, we can call globalhost.connectionmanager.gethubcontext<simplehub> () where we need to send the message. Get clients in clients. Get clients and send a message we'd better write a singleton pattern, because this requirement fits into a single case, with detailed code in group chat.

3, SIGNALR realization Group Chat

The above introduction and code can be implemented B=>s and s=>b, the implementation of group chat and separate chat is relatively simple.

Because the function is relatively simple, all I put the user name in the cookie, also said the first time in the need to set up a cookie.

There is also the need to implement onconnected, ondisconnected, and onreconnected in the hub, and then set up users and ConnectionID and statistics online users in the method for chat use.

Hub Code

<summary>//SignalR Hub Group Chat class///</summary> [Hubname ("Groupchathub")]//tag name for JS call public class Groupchat Hub:hub {//<summary>///user name//</summary> private string UserName {get {var UserName = Context.req  uestcookies["USERNAME"]; return userName = = null?  "": Httputility.urldecode (Username.value); }}///<summary>//Online users///</summary> private static dictionary<string, int> _onlineuser = new Dicti Onary<string, int> ();   <summary>///Start connection///</summary>//<returns></returns> public override Task onconnected () {  Connected (); Return base. Onconnected (); }//<summary>//re-link///</summary>/<returns></returns> public override Task onreconnected  () {Connected (); Return base. Onreconnected (); } private void Connected () {//Handling online personnel if (!_onlineuser.containskey (UserName))///If the name does not exist, it is a new user {//join the online person _onlineus Er.  ADD (UserName, 1); Send an online person to the client Clients.All.puBlshuser (_onlineuser.select (i = I.key));  Send a Join chat message to the client CLIENTS.ALL.PUBLSHMSG (formatmsg ("System Message", UserName + "Join chat");  } else {//If the user already exists, the number of online links is +1 _onlineuser[username] = _onlineuser[username] + 1; }//Join the Hub Group in order to send a separate message groups.add (Context.connectionid, "group-" + UserName); }///<summary>//End connection///</summary>/<param name= "stopcalled" ></param>//<returns> </returns> public override Task ondisconnected (bool stopcalled) {//number of people links-1 _onlineuser[username] = _onlineuser[u  Sername]-1;  Determine if all links are disconnected if (_onlineuser[username] = = 0) {//Remove online personnel _onlineuser.remove (UserName);  Send the online personnel Clients.All.publshUser (_onlineuser.select (i = I.key)) to the client;  Send an exit Chat message to the client CLIENTS.ALL.PUBLSHMSG (formatmsg ("System Message", UserName + "Exit chat");  }//Remove Hub Group groups.remove (Context.connectionid, "group-" + UserName); Return base. Ondisconnected (stopcalled); }///<summary>///Send message for client to call///</summary>//<param Name= "User" > Username, if 0, is sent to everyone </param>//<param name= "MSG" > Message </param> public void sendmsg (string  User, String msg) {if (user = = "0") {//Send to all user messages CLIENTS.ALL.PUBLSHMSG (formatmsg (UserName, msg));  } else {////is sent to its own message//clients.group ("group-" + UserName). Publshmsg (Formatmsg (UserName, msg));  Sent to the selected person//clients.group ("group-" + user). Publshmsg (Formatmsg (UserName, msg)); Send to Yourself Message clients.groups (new list<string> {"group-" + UserName, "group-" + user}). publshmsg (Formatmsg,  msg)); }}///<summary>///format sent messages///</summary>//<param name= "name" ></param>//<param name= " MSG "></param>///<returns></returns> Private dynamic Formatmsg (string name, String msg) {return NE W {name = name, msg = Httputility.htmlencode (msg), time = DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss")}; } }

JS Code

<script type= "Text/javascript" > $ (function () {//link hub var ticker = $.connection.groupchathub;  $.connection.hub.start (); The receiving server sends the message $.extend (ticker.client, {//Receive Chat message publshmsg:function (data) {$ ("#msg"). Append ("<li><span c lass= ' P ' > + data. Name + ":</span>" + data. MSG + "<span class= ' time ' >" + data.  Time + "</span></li>") $ ("#msg"). Parents ("P") [0].scrolltop = $ ("#msg"). Parents ("P") [0].scrollheight;   },//receive the online person, and then join select for a separate chat select Publshuser:function (data) {$ ("#count"). Text (data.length);   $ ("#users"). empty ();   $ ("#users"). Append (' <option value= ' 0 "> All </option> '); for (var i = 0; i < data.length; i++) {$ ("#users"). Append (' <option value= "' + data[i] + '" > ' + data[i] + ' <  /option> ')}});  Send Message button $ ("#btn-send"). Click (function () {var msg = $ ("#txt-msg"). Val (); if (!msg) {alert (' Please enter content! ');  return false;  } $ ("#txt-msg"). Val (');  Proactively send messages, incoming send to WHO, and send content. Ticker.server.senDmsg ($ ("#users"). Val (), MSG); }); }); </script>

HTML code

Github.com/emrys5/signalrgroupchatdemo

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.