asp.net use signalr to implement chat room functions _ practical skills

Source: Internet
Author: User
Tags prev unique id

First, the introduction
In the previous article "ASP.net use signalr to achieve cool end to end chat function", I introduced to you how to achieve end-to-end chat function, in this article will be like everyone how to use SIGNALR to achieve group chat such functions.

Second, the realization of ideas
To achieve the function of group chat, first we need to create a room, then each online user can join in 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 class library? The answer is yes.

The Igroupmanager interface provides the following methods
/functions: Adding a connection ID to a group
//Context.connectionid connection ID, and each page connection hub produces a unique ID
// Roomname the name of the grouping
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 mass messages to all users in the room/ 
/Room: Group name
//New String[0]: filter (not sent) Array of connection IDs
 Clients.group (Room, New string[0]). Clientmethod

The code above is the core approach to implementing group chats. Groups object plainly is the SIGNALR class library maintenance of a list object, in fact, we can completely maintain a dictionary<string, list<string>> this object, create a room, We add the name of the room and the ConnectionID of the client who enters the room to the dictionary, and then in the chat room, when we send a 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 to realize the principle of the chat room.

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

<summary>///User Class///</summary> public class User {///<summary>///user ID///

  Ary> public string UserId {get; set;}

  <summary>///User's connection set///</summary> public list<connection> connections {get; set;}

  <summary>///User Room collection, a user can add multiple rooms///</summary> public list<chatroom> rooms {get; set;}
   Public User () {connections = new list<connection> ();
  Rooms = new list<chatroom> ();

  The public class Connection {//connection ID public string ConnectionID {get; set;}
  User Agent public string useragent {get; set;} 
 Connect public bool Connected {get; set;} ///<summary>///Room class///</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 simulate DBCO in the EFntext///</summary> public class Chatcontext {public list<user> the 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 a hub:

[Hubname ("Chatroomhub")] public class Groupshub:hub {public static chatcontext DbContext = new Chatcontext (); #region Ihub members//overriding hub Connection Events public override Task onconnected () {//query user var user = DbContext.Users.Firs

   Tordefault (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 event public override Task ondisconnected (bool stopcalled) {//query user var user = Dbcontext.users.f for hub connection disconnection

   Irstordefault (U => u.userid = = Context.connectionid);

    if (user!= null) {//delete users DbContext.Users.Remove; Removes the user foreach (var item in user) from the room. Rooms) {Removeuserfromroom (item).
    Roomname);
   }Return to base.
  Ondisconnected (stopcalled); #endregion #region Public Methods//update room list for all users public void Updateroomlist () {var itme = dbcontext.ro OMs.
   Select (P => new {p.roomname}); var jsondata = jsonhelper.tojsonstring (itme.
   ToList ());
  Clients.All.getRoomlist (Jsondata);  }///<summary>///join chat room///</summary> public void Joinroom (string roomname) {//query chat room var

   room = DbContext.Rooms.Find (p => p.roomname = = roomname);

   Presence is added if (room = null) return; Find out if this user var isexistuser = room exists in the room.

   Users.firstordefault (U => u.userid = = Context.connectionid);
    Does not exist, add if (Isexistuser = = null) {var user = DbContext.Users.Find (u => u.userid = = Context.connectionid); User.
    Rooms.add (room); Room.
    
    Users.add (user);

    Add the client's connection ID to the group groups.add (Context.connectionid, roomname);
   Call the local JS (show room) clients.client (Context.connectionid). Joinroom (Roomname) of this connected user;
} else {    Clients.client (Context.connectionid). ShowMessage ("Do not repeat the room!");  }///<summary>///create chat room///</summary>///<param name= "Roomname" ></param> public
   void Createroom (String roomname) {var room = DbContext.Rooms.Find (a => a.roomname = = roomname);

    if (room = = null) {var CR = new Chatroom {roomname = roomname};

    Add the room to the 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 exists var room = DbContext.Rooms.Find (a => a.ro

   Omname = = Roomname);
    exists to delete if (room = = null) {clients.client (Context.connectionid). ShowMessage ("Room name does not exist!");
   Return //Find the user to delete var user = room.
   Users.firstordefault (a => A.userid = = Context.connectionid); Remove this user room.
   Users.remove (user); If the number of rooms is 0, deleteRoom if (room.
   Users.count <= 0) {DbContext.Rooms.Remove (room);

   } groups.remove (Context.connectionid, roomname);
  Prompt client Clients.client (context.connectionid). Removeroom ("Exit success!");  ///<summary>///send messages to all users in the room///</summary>///<param name= "room" > Room name </param>/// <param name= "message" > Info </param> public void SendMessage (string room, String message) {//Calling all clients in the room SendMessage method//Because when you join the room, the client's ConnectionID has been added to the Groups object, and all the connection IDs in the room can be found by the name of the room. We can actually implement the group method ourselves,
   We only need to use list to record all the ConnectionID//Then call Clients.clients (connectionidlist), the parameter is the array of connection IDs we record.
  Clients.group (room, new string[0]). SendMessage (room, message + "" + DateTime.Now);
 } #endregion}


3. The code implementation for the SIGNALR server above is complete, so let's take a look at the implementation of the client view:

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

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

<summary>
 ///JSON help class
 ///</summary> public
 class Jsonhelper
 {
  ///<summary >
  ///generate JSON strings from an object information
  ///</summary>
  ///<param name= "obj" ></param>
  ///< Returns></returns> public
  static string toJSONString (Object obj)
  {
   return Jsonconvert.serializeobject (obj);
  }

  <summary>
  ///generates objects from the 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, on the specific look at the function of the chat room operation effect, the specific operation effect as shown in the following figure:

SOURCE Download: Signalrchatroom

Here, all the content of this article is finished, then I will implement an article on how to use SIGNALR to achieve the function of sending pictures.

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.