ASP. NET uses SIGNALR to achieve cool end-to-end chat capabilities

Source: Internet
Author: User
First, Introduction

SIGNALR has been described in detail in the previous article, and its applications in ASP. NET MVC and WPF are briefly described. In the previous blog is the introduction of the bulk of the implementation of the message, however, for the SIGNALR is for real-time chat and born, natural less than QQ-like end-to-end chat. This blog post will show you how to use SIGNALR to achieve similar functions of QQ chat.

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

Before introducing the implementation, I first introduced 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, and this Code, which represents the sendMessage that invokes all clients. The SIGNALR hub enables real-time communication between the client and the server. That to achieve end-to-end chat, nature will not be like all clients send messages, and can only send a message to a specific client, otherwise it is not a mess, no privacy. So how can I send a message to a specific client? This problem is the key to our end-to-end chat capabilities.

We send the Clients object in addition to the all property, there are other properties, you can press F12 in VS to see all the properties or methods of the clients object, as defined below:

Public interface ihubconnectioncontext<t>{t all {get;}//Represents all clients T allexcept (params string[] Excludeconnectionids ); All clients except the parameters in the T client (string ConnectionID); Specific client, this method is our implementation of the end-to-end chat key T clients (ilist<string> connectionids); The client-side T Group in the parameter (string groupName, params string[] excludeconnectionids); Specify the client group, this is also the key to implement 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 marked for uniqueness, and SIGNALR assigns it a connnectionid so that we can find a specific client by Connnectionid. In this way, when we send a message to a client, in addition to passing the 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 based on the incoming ConnectionID. This also completes the end-to-end chat function. In addition, if the user is not in the line, the server can save the message to the database, and so on when the corresponding client on-line, and then from the database to see if the client has a message to push, if so, from the database to pull the data, the data is pushed to the client. (However, the function of server-side caching of data this post has not been implemented, here is the introduction is to let everyone understand QQ a principle of implementation).

Below, we will comb the bottom-end chat function to realize the idea:

When the client logs in, it records the client's Connnectionid and joins the user into a static array, which is recorded for all online users.
Users can click on the user chat in the online user, when sending a message, you need to send ConnectionID to the server side.
The service side calls Clients.client (Connnection) based on the incoming message content and ConnectionID. SendMessage method to forward to the corresponding client.

Third, the realization of cool chat function core code

With the implementation 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> ();//Online User column Table///<summary>///Login///</summary>/<param name= "userId" > User id</param>//<param name= "UserName" > User name </param> public void Connect (string userId, String userName) {var connnectid = Context.connection   Id;   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 person onlineusers.add (new UserInfo {ConnectionID = connnectid, UserID = userid, UserName = UserName, Las  Tlogintime = DateTime.Now}); }//All clients synchronize Online user Clients.All.onConnected (Connnectid, UserName, onlineusers); }//<summary>Send private chat//</summary>//<param name= "Touserid" > Receiver user Connection id</param>//<param name= "message" >    Content </param> public void Sendprivatemessage (string touserid, String message) {var fromuserid = 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 (Fromuserid,   Fromuser.username, message);  Send to caller user//Clients.Caller.sendPrivateMessage (Touserid, fromuser.username, message);  } else {//indicates that the other party is not online Clients.Caller.absentSubscriber (); }}///<summary>/////</summary>//<param name= "stopcalled" ></param>//<returns& Gt;</returns> public override Task ondisconnected (bool stopcalled) {var user = Onlineusers.firstordefault (U = U.connectionid = = Context.connectioniD); To determine if the user exists, delete the if (user = = null) return base.   Ondisconnected (stopcalled); Clients.All.onUserDisconnected (user. ConnectionID, user. UserName);    Call client user offline notification//delete user onlineusers.remove (username); Return base. Ondisconnected (stopcalled); } }

Above is the main implementation of the server, next look at the implementation of the client code:

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

The above is just a list of some core code implementations. In addition, in order to achieve the cool effect, here is a jquery plugin: layer, the official site is: http://layer.layui.com/. This plugin mainly in order to achieve the pop-up box and pop-up layer effect, to achieve cool chat effects, you need to write JS code, because I am not very familiar with the front end, so this JS effect code is also the reference network implementation. If you want to run the view effect, we recommend to the end of the article download source code to run.

Iv. Final Effect

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



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.