ASP. NET uses SIGNALR to implement chat room functions

Source: Internet
Author: User
Tags unique id
First, Introduction
In the previous article, "ASP. NET uses SIGNALR for cool end-to-end chat," I'll show you how to implement end-to-end chat, in this article will be like how you can use SIGNALR to achieve the function of group chat.

Second, the realization of ideas
To realize the function of group chat, first we need to create a room, then each online user can join this room for group chat, we can set a unique name for the room as a logo. Is there such an existing method in the SIGNALR library? The answer is yes.

The Igroupmanager interface provides the following methods/functions: Adding the connection ID to a group//Context.connectionid connection ID, each page connection hub produces a unique id//roomname grouping name Groups.add ( Context.connectionid, Roomname); Function: Remove the connection ID from a group groups.remove (Context.connectionid, roomname); The Ihubconnectioncontext interface provides the following methods//calling client methods to send bulk messages to all users in the room//Rooms: Group name//New String[0]: filter (not send) array of connection IDs Clients.group ( , new String[0]). Clientmethod


The code above is the core method of implementing group chat. Groups object in other words, SIGNALR Class Library maintenance of a list of objects, in fact, we can fully maintain a dictionary<string, list<string>> this object, create a room, We add the room name and the ConnectionID of the client that enters the room into this dictionary, and then in the chat room to send the message, we find all the ConnectionID to join the group chat according to the room name, and then call Clients.clients ( Ilist<string> Connectionids) method to bulk the message to each client. The above is the realization of the principle of the chat room.

Third, the use of SIGNALR to implement the function of the chat room
Figure out the realization of the idea, then we will look at the specific implementation code, at the same time you can control the code to control the implementation of the previous ideas.
First look at the implementation code of the entity classes involved in the chat room feature:

<summary>///user class///</summary> public class User {///<summary>//ID//</summary>   public string UserId {get; set;}   <summary>///user connection Set///</summary> public list<connection> Connections {get; set;}   <summary>///user room collection, one user can join multiple rooms///</summary> public list<chatroom> Rooms {get; set;}   Public User () {Connections = new list<connection> ();  Rooms = new list<chatroom> ();   }} public class Connection {//connection ID public string ConnectionID {get; set;}  User Agent public string useragent {get; set;}   Whether to connect public bool Connected {get; set;}}   <summary>//room type///</summary> public class Chatroom {//Room name public string Roomname {get; set;}   User Collection Public list<user> users {get; set;}  Public chatroom () {Users = new list<user> (); }}///<summary>///Context class to emulate DbContext///</summary> public class Chatconte in EFXT {public list<user> Users {get; set;}   Public list<connection> Connections {get; set;}   Public list<chatroom> Rooms {get; set;}   Public Chatcontext () {Users = new list<user> ();   Connections = new list<connection> ();  Rooms = new list<chatroom> (); } }



2. Next, let's see the implementation of the hub:

[Hubname ("Chatroomhub")] public class Groupshub:hub {public static Chatcontext DbContext = new Chatcontext (); #region Ihub members//overriding hub Connection event public override Task onconnected () {//query user var user = DbContext.Users.FirstOrDe    Fault (U = u.userid = = Context.connectionid);     if (user = = null) {user = new user {UserId = Context.connectionid};   DBCONTEXT.USERS.ADD (user);   }//Send room list var items = DbContext.Rooms.Select (p = = new {p.roomname}); Clients.client (this. Context.connectionid). Getroomlist (jsonhelper.tojsonstring (items.   ToList ())); Return base.  Onconnected (); }//overriding hub connection disconnected event public override Task ondisconnected (bool stopcalled) {//query user var = DbContext.Users.FirstO    Rdefault (U = u.userid = = Context.connectionid);     if (user! = null) {//delete user DbContext.Users.Remove (username); Remove the user foreach (var item in user) from the room. Rooms) {Removeuserfromroom (item.    Roomname); }} return base. Ondisconnected (stopcalLED); } #endregion #region Public Methods//update room list for all users public void Updateroomlist () {var itme = DbContext.Rooms.Sel   ECT (p = new {p.roomname}); var jsondata = jsonhelper.tojsonstring (itme.   ToList ());  Clients.All.getRoomlist (Jsondata);  }///<summary>//Join chat rooms///</summary> public void Joinroom (string roomname) {//query rooms var room =    DbContext.Rooms.Find (p = p.roomname = = roomname);    If present, add if (= null) return; Find out if this user var isexistuser = room is present in the rooms.    Users.firstordefault (U = u.userid = = Context.connectionid);    If not present then add if (Isexistuser = = null) {var user = DbContext.Users.Find (U = u.userid = = Context.connectionid); User.    Rooms.add (guest); Room.         Users.add (user);     Add the connection ID of the client to the group inside Groups.add (Context.connectionid, roomname);   Call this connection user's local JS (show room) clients.client (Context.connectionid). Joinroom (Roomname);   } else {clients.client (Context.connectionid). ShowMessage ("Do not re-join the room!");  }  } <summary>//Create a chat room///</summary>//<param name= "roomname" ></param> public void Create   Roomname (string) {var = DbContext.Rooms.Find (A = = A.roomname = = roomname);     if (* = null) {var CR = new Chatroom {roomname = roomname};     Add room to list DbContext.Rooms.Add (CR);    I joined the chat room joinroom (roomname);   Updateroomlist ();   } else {clients.client (Context.connectionid). ShowMessage ("Duplicate room name!"); }} public void Removeuserfromroom (string roomname) {//Find room for existence of var rooms = DbContext.Rooms.Find (A = A.roomnam    E = = Roomname);    exists then go to delete if (room = = null) {clients.client (Context.connectionid). ShowMessage ("The name does not exist!");   Return }//Find the user you want to delete.   Users.firstordefault (A = A.userid = = Context.connectionid); Remove this user's.   Users.remove (user); If the number of rooms is 0, delete the room if.   Users.count <= 0) {DbContext.Rooms.Remove (guest); } groups.remove (Context.connectionid, ROomname);  Tip Client Clients.client (Context.connectionid). Removeroom ("Exit succeeded!"); }///<summary>///For all users in the room///</summary>//<param name= "Room" > Name </param>//< param name= "message" > Information </param> public void SendMessage (string room, String message) {//Call sendmess for all clients in the Chamber The Age method//Because the client's ConnectionID has been added to the groups object when it joins the room, all the connection IDs in the room can be found according to the room name//We can actually implement the group method ourselves,   We only need to use list to record all ConnectionID//and then call Clients.clients (Connectionidlist), which is the array of connection IDs we recorded.  Clients.group (Guest, new String[0]). SendMessage (guest box, message + "" + DateTime.Now); } #endregion}



3. The above SIGNALR service-side code implementation has been completed, then let us look at the implementation of the client view:

@{Layout = null;} <! DOCTYPE html> 


4. After 3 steps above, the function of the chat room has been completed, before looking at the specific effect, there is a helper class code:

<summary>///JSON helper class///</summary> public class Jsonhelper {///<summary>///  from an object information generation J Son string///</summary>//  <param name= "obj" ></param>//  <returns></returns > Public  static string toJSONString (Object obj)  {   return jsonconvert.serializeobject (obj);  }   <summary>///  Generate objects from JSON string///</summary>//  <typeparam name= "T" ></ typeparam>//  <param name= "jsonstring" ></param>///  <returns></returns> Public  static T toobject<t> (string jsonstring)  {   return jsonconvert.deserializeobject<t> (jsonstring);  } }


Iv. Results of operation

Next, just look at the function of the chat room to run the effect, the specific operation effect as shown:

Here, all the content of this article is finished, next I will implement how to use SIGNALR to achieve the function of the hair picture.

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.