asp. net SignalR and LayIM2.0 with easy implementation of the web chat room (ix) using Redis to implement user online offline status message processing (a)

Source: Internet
Author: User

Objective

The previous article briefly explained the use of Redis to cache online user Logic. Space is also relatively small, this article will be in detail to realize the User's offline notification, image effect conversion Function. In addition, the code and development ideas will be described in Detail.

Effect Show

There are currently three users, user1,user2,user3. will simply show the user on-line, offline message push Effect.

Figure One: User 1 login, at this time friends are not online. (avatar is gray, Google Chrome)

  

Figure Two: User 1 login (open 360 browser impersonate user 1 login), at this time Google browser users receive the user online notification, icon lit

  

Figure Three: User 2 login (open sogou Browser simulation User 2 login), at this time Google browser users receive the user online notification, icon lit

  

Figure Four: Three users are online (three browsers)

  

Figure V: Google Browser users offline (the other two users receive the offline message, avatar to black and White)

  

Practical explanation

Imperfect place:

1. Users online or offline will have inaccuracies, need to re-refresh the page to

2. The user icon in the group is not currently processed

3. The icon to open the Chat window is also not processed (if the user is not on the line, the icon is still lit)

Now get to the point, all backstage operations are to provide data to the front end. Then the front-end as long as one thing can, receive messages, according to users on the offline change the status of the user Picture. My method is to use a third-party js. Official website: https://en.wikipedia.org/wiki/Grayscale, I copied JS to the local, and encapsulated into Layui can be quoted Js.

  

As we said before, we define a gray plugin and grayscale the Object. Small partners don't forget to configure the JS on the Homepage.

    //Custom Moduleslayui.extend ({signalr:'/SCRIPTS/SIGNALR/SIGNALR', Autohub:'/scripts/signalr/autohub',//auto-generatedHub'/scripts/signalr/hub', Gray:'/scripts/gray'//control picture Black and white JS               });

then, What we have to do is very simple. Want to put which picture gray, call similar to the following method, then the picture will be replaced by a base64 gray picture, the effect in the top, I believe you have Seen.

    var imgs = $ ("img[data-status= ' hide ']");     if (imgs.length) {
Grayscale (imgs); }

As we all know, we will have friends list information when we first enter the Layim interface. So the previous article on using Redis to store online lists of users would be Useful. We found the base method (get user base information, friend information, group information, etc.)

                 //User group Information                varRowfrienddetails = ds. tables[2]. Rows.cast<datarow> (). Select (x =Newgroupuserentity {id= x["UID"]. ToInt (), Avatar= x["Avatar"]. ToString (), GroupID= x["GID"]. ToInt (), Remarkname= x["Remarkname"]. ToString (), username= x["Nickname"]. ToString (), sign= x[" sign"]. ToString (),//the field before status is empty, and now we add his online status, the Isonline method receives a UserID parameter, reads from the Redis cache whether the user is online and returnsStatus = LayIMCache.Instance.IsOnline (x["UID"]. ToInt ())?"Online":"Hide"                }). OrderByDescending (x= x.status);//this will be based on whether the user is online this field sort, to ensure that online users are at the top of the Friends list

The part of the comment is where the change is, so we look at the JSON format information returned after initializing the Layim.

  

See where the red frame is painted, my two friends are not online (hide). however, the icon is still bright, how to do, then we need to wait for data loading after we use the top of the processing icon JS Processing. yes, we have to change the Layim code again. (PS: The official is not recommended to change the ha, or upgrade is not good integration) a lot of students want to change the code, I simply say I change the code thinking. In fact, no matter what JS to do, and ultimately it is for the HTML service, so we find the user picture of the Label:

  

It's a processed picture, but it doesn't matter, we just care, where this img tag can be. ( note: Data-status is I add, that is, to change the source code is to add such a thing ) and then we find the Layim code, from the template inside to find it.

  

The red box is where I changed. After We've changed it, we're looking at the main interface, so we know which of the IMG tags is going to be processed into black and White. It is then called in the Ready method:

  

Initstatus:function () {                //loop detection requires a black and white avatar                //the reason for using interval here is that the picture may still be loaded and the black and white effect is not the problem                 this. Useravatarinterval = SetInterval (function () {                    //gets the IMG object with the Hide tag                    varIMGs = $ ("img[data-status= ' Hide ']"); if(imgs.length) {//set black and white effectsGrayscale (imgs); //Stop Loopclearinterval (other.useravatarinterval); }                }, 200); //stop after more than five seconds (for insurance purposes)SetTimeout (function() {clearinterval (other.useravatarinterval); }, 5000); },

So we can finish the initialization, know which friend is online, which friend is not online. Now what is the problem, obviously, join my current friends are not on the line, then the icons are BLACK. If a friend goes online, I don't refresh the page, but its icon is still black, right? so, we need to use the singalr, return to the message push, the following we have to do is when the user on-line or after the offline send a message to their friends to Push. because, I'm already using redis, so I'm just going to use Redis to save Everyone's friends List. But the difference is that the friend list cache needs to be updated constantly, such as adding friends, after deleting friends and so On. here, I didn't do so much trouble, I set a day's expiration time, so that every day after the Update. Take a look at the Get buddy list code:

 #regionGet a friend list for a user/// <summary>        ///get a friend list for a user/// </summary>        /// <param name= "userid" >User ID</param>        /// <returns>return format as follows "" or "10001,10002,10003"</returns>         public stringGetuserfriends (intUserid) {            //Read Cache First            varFriends =LayIMCache.Instance.GetUserFriendList (userid); //if the cache does not have            if(friends = ="")            {                //read from database, save to cacheFriends =_dal.                Getuserfriends (userid);            LayIMCache.Instance.SetUserFriendList (userid, friends); }            returnfriends; }        #endregion

Because the gray head is base64, if the user is online, we need to pass the User's original avatar to the front, and then replace the avatar. so, This cache I have for the moment the avatar information is also saved in (business coupling). Look at the values in Redis:

  

, the user 10003 friend Is: 10004,10005. The values are in the Form: Useravatar + $LAYIM $ + friendids. again, we add a way to send the User's downline message in Hubserver:

  

  /// <summary>        ///send a message to the User's upper and lower lines/// </summary>         public Static voidSenduseronofflinemessage (stringUseridBOOLOnline=true)        {            intUserID =Userid.toint (); //1. Get all the Friends of the user            varUsers =LayimUserBLL.Instance.GetUserFriends (userid); //no friends, no messages            varFriends = Users. Split (New string[] {"$LAYIM $"}, stringsplitoptions.removeemptyentries); if(friends. Length = =2)            {                varAvatar = friends[0]; varNotifyusers = friends[1]; //2. Send the user to the offline notificationUseronofflinemessage message =Newuseronofflinemessage {avatar=avatar, Online=online, userid=userid}; SendMessage (message, notifyusers, chattoclienttype.useronofflinetoclient,true); }        }

The method is to get the User's friend and avatar information in the cache, and then compose a new message and send it. So where is this method called? We're still back in the Layimhub Code.

 /// <summary>        ///Establish a connection/// </summary>        /// <returns></returns>         public OverrideTask onconnected () {//Add the current user to the Redis online user cacheLayIMCache.Instance.OperateOnlineUser (currentonlineuser); //Send user online messageHubServer.HubServerHelper.SendUserOnOffLineMessage (currentuserid); returnClients.Caller.receiveMessage ("Connection Successful"); }        /// <summary>        ///Lost connection/// </summary>        /// <param name= "stopcalled" ></param>        /// <returns></returns>         public OverrideTask ondisconnected (BOOLStopcalled) {            //Remove the Current User from the online user listLayIMCache.Instance.OperateOnlineUser (currentonlineuser, isdelete:true); //Send user downline messageHubServer.HubServerHelper.SendUserOnOffLineMessage (currentuserid, online:false); returnClients.Caller.receiveMessage ("Lost connection"); }        /// <summary>        ///re-connect/// </summary>        /// <returns></returns>         public OverrideTask onreconnected () {//Add the current user to the Redis online user cacheLayIMCache.Instance.OperateOnlineUser (currentonlineuser); //Send user online messageHubServer.HubServerHelper.SendUserOnOffLineMessage (currentuserid); returnClients.Caller.receiveMessage ("re-connect"); }

haha, is not found to use onconnected,onreconnected,disconnected method can do a lot of things ah. Then we can add a branch on the index Page.

  

Let's run it first to see the effect:

  

It is good for us to define the message as a uniform format so that we can handle it according to our own business and accept the message as an interface: receiveMessage. You can see the msg with the User's avatar, online status, and User ID. Once we get this information, we'll have to deal with it.

  

            //Reset your avatar, black and white or lightResetuseravatar:function(obj) {varAvatar = obj.avatar, Online = obj.online, UserID =obj.userid;
This code is to locate the avatar under the uservarImgobj = $ (' #layim-friend ' + userid). find (' img ')); if(imgobj.length) {if(obj.online) {//If you are online, change your avatar to your original avatar, which is a non-black and white avatarImgobj.attr (' src ', avatar); } Else { //Place the Avatar blackGrayscale (imgobj); } } }

So far, functional development is Over.

Summarize

This article is relatively more than the previous one, involving content, redis cache, update and so On. Picture black and white processing, signalr message processing. As well as source code Reading.

In short, the most important part is SIGNALR this push if stable, as long as the message can be delivered to the client, then let the client to Handle. We also pay attention to learning to customize the message Content. Make sure your business is Smooth.

  

Next Trailer : No (i don't know what to write, then watch It)

Want to learn the small partner, can follow my blog oh, my qq:645857874,email:[email protected]

GitHub:https://github.com/fanpan26/LayIM_NetClient/( no source code oh, because Layim need to be authorized, please understand )

asp. net SignalR and LayIM2.0 with easy implementation of the web chat room (ix) using Redis to implement user online offline status message processing (a)

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.