asp.net use signalr to implement cool end to end chat function _ practical skills

Source: Internet
Author: User
Tags live chat

First, the introduction

SIGNALR has been introduced in detail in the previous article, and its application in asp.net MVC and WPF is briefly described. In the blog is the introduction of the mass message of the implementation, however, for SIGNALR is to live chat, naturally less than the same as QQ end-to-end chat. This blog post will explain how to use SIGNALR to achieve a similar function of QQ chat.

Second, the use of SIGNALR to achieve end-to-end chat ideas

Before I introduce the specific implementation, I will first introduce the idea of using SIGNALR to implement End-to-end chat. I believe you have seen Clients.All.sendMessage (name, message) in the previous article, such code, which represents the invocation of SendMessage of all clients. The SIGNALR hub enables real-time communication between the client and the server. That to achieve end-to-end chat, nature can not be like all clients to send messages, but only to a specific client to send messages can, otherwise it is not a mess, there is no privacy. So how can you send a message to a particular client? This problem is the key to our End-to-end chat function.

We send the Clients object in addition to the all attribute, and you can press F12 in VS to view all the properties or methods of the clients object, as defined below:

 Public interface ihubconnectioncontext<t>
 {
 t all {get;}//On behalf of all clients

 T allexcept (params string[) exclu Deconnectionids); In addition to all client T-clients
 (string ConnectionID) in the parameter, this method is the key T Clients for end-to-end chat
 (ilist<string> Connectionids); The client-side
 T Group (string groupname, params string[] excludeconnectionids in the parameter);//Specify the client group, which is also the key to implementing the group chat
 T Groups ( Ilist<string> groupnames, params string[] excludeconnectionids);
 T User (string userId); Specific user
 T users (ilist<string> userids);//user in Parameter
 

In SIGNALR, each client is marking its uniqueness, SIGNALR assigns it a connnectionid so that we can find a specific client through Connnectionid. In this way, when we send a message to a client, in addition to the incoming message, we need to send the ConnectionID input to the other side, so that the server can forward the corresponding message to the corresponding client according to the incoming ConnectionID. This also completes the End-to-end chat function. In addition, if the user is not a line, the server can save the message to the database, and so on the corresponding client online, and then from the database to see if there is a message to push the client, if any, from the database to pull data, the data to the client. (But this, server-side caching of data features this blog is not implemented, here is to let everyone understand the principle of QQ implementation).

Here we will comb the end of the chat function to realize the idea:

When the client logs in, it records the client's Connnectionid and adds the user to a static array that records all online users.
Users can click on users in the online chat, when sending messages, you need to ConnectionID to the server.
The service side invokes Clients.client (Connnection) based on the incoming message content and ConnectionID. SendMessage method to forward to the corresponding client.

Three, the realization cool chat function core code

With the realization of ideas, the realization of the function is also handy, next, let us first look at the code in the Chathub:

public class Chathub:hub {//static property public static list<userinfo> onlineusers = new list<userinfo> (); Line user list///<summary>///login///</summary>///<param name= "userId" > User id</param>///-<pa Ram Name= "UserName" > Username </param> public void Connect (string userId, String userName) {var connnectid = Contex

  T.connectionid;
  if (Onlineusers.count (x => X.connectionid = = connnectid) = = 0) {if (Onlineusers.any (x => x.userid = = UserId)) {var items = onlineusers.where (x => x.userid = = UserId).
   ToList (); foreach (var item in items) {clients.allexcept (Connnectid). onuserdisconnected (item. ConnectionID, item.
   UserName);
  } onlineusers.removeall (x => x.userid = = UserId); 
   }//Add online personnel onlineusers.add (new UserInfo {ConnectionID = Connnectid, UserId = UserId, UserName = UserName,
  Lastlogintime = DateTime.Now}); ///All clients sync Online user Clients.All.onConnected (Connnectid, UserName, OnliNeusers); ///<summary>///Send private chat///</summary>///<param name= "Touserid" > Recipient user Connection id</param>///&L T;param name= "message" > Content </param> public void Sendprivatemessage (string touserid, String message) {var fromu

  Serid = Context.connectionid;
  var touser = onlineusers.firstordefault (x => X.connectionid = = Touserid);

  var fromuser = onlineusers.firstordefault (x => X.connectionid = = Fromuserid); if (touser!= null && fromuser!= null) {//Send to Clients.client (Touserid). Receiveprivatemessage (Fromus

  Erid, fromuser.username, message);
  Send to caller user//Clients.Caller.sendPrivateMessage (Touserid, fromuser.username, message);
  else {//indicates that the other person is not online Clients.Caller.absentSubscriber (); Call///</summary>///<param name= "stopcalled" ></param>///<re///<summary>///disconnected Turns></returns> public override Task ondisconnected (bool stopcalled) {var user = OnliNeusers.firstordefault (U => u.connectionid = = Context.connectionid); To determine if the user exists, then delete the if (user = = null) return base.

  Ondisconnected (stopcalled); Clients.All.onUserDisconnected (user. ConnectionID, user. UserName);


  Call the client user offline notification//delete user onlineusers.remove (users); Return base.
 Ondisconnected (stopcalled);
 }
 }

Above is the main implementation of the service side, then look at the implementation code for the client:

 <script type= "Text/javascript" > var systemhub = $.connection.chathub; /Connect IM server successfully//mainly update online user systemHub.client.onConnected = function (ID, userName, allUsers) {var node = Chatcore.node,
  MYF = Node.list.eq (0), str = ', i = 0;
  Myf.addclass (' loading ');
  Onlinenum = Allusers.length; if (Onlinenum > 0) {str = ' <li class= ' chatcore_parentnode Chatcore_liston ' > ' + '  

Just a few of the core code implementations are listed above. In addition, in order to achieve the cool effect, here uses a jquery plug-in: layer, the official website: http://layer.layui.com/. This plug-in mainly in order to realize the pop-up box and pop-up layer effect, to achieve cool chat effects, you need to write the JS code, because I am not very familiar with the front-end, so this JS effect code is also a reference to the realization of the network. If you want to run the viewing effect, we recommend to the end of the article download source to run.

Iv. Final Effect

After the introduction of the implementation and implementation of the code, since it is our exciting moment, it is to see if we realize whether the function can meet the needs, in addition to meet the basic chat function, but also to see if the interface is cool enough.

V. Summary

Watching the above effect, is not very cool it. This is the end of this article, and I will continue to explain how to use ASP.net signalr to implement the chat room function in the next article.

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.