Web chat rooms promptly clean up offline users (the easiest way)

Source: Internet
Author: User

Recently, when I was working on a chat room, I had to worry about how to promptly clean up offline users,

I found very wrong information on the Internet. I feel that many people are asking this question. The answer is basically the following two.

1. Use js to control page events and process and judge in onUnload and onbeforeunload events. Although a good one is found

Determine whether the user refreshes the page or closes the page, but the problem is only possible under IE.

2. Use the session. The delay is too high. It takes at least 20 minutes to destroy the default session, so you can pass this without thinking about it.

Then it seems that the collected articles basically refer to these two types. Of course, there is also an article saying that it can solve all the problems, but the code is too long and I think it is too big, the idea is not clear.

Don't talk nonsense. Let me share it with you.

The example in my chat room is very simple: a login page (login. aspx), a chat room (index. aspx)

1. Field ID, name, password, and lasttime in the User table
Lasttime is used to obtain the last online message.

2. Enter name and password on the login page. When you click the login button, verify that the user name and password are correct,
If the information is correct, save the user information in sessionl and update the current user.
If (checklogin (name, PWD, out user) {// return bool + User (the output value is the object successfully verified)
User. lasttime = datetime. Now; // change the logon time
Session ["user"] = user;
Usermanager. Update (User); // update the user to the database, mainly to update the lasttime Field
Response. Redirect ("index. aspx ");
} Else {
// Login Failed
}

3. After successful login, the index. ASPX page is displayed.
// JQ
<SCRIPT type = "text/JavaScript" Language = "JavaScript" src = "JQ/jquery-1.4.1.min.js"> </SCRIPT>
<SCRIPT type = "text/JavaScript" Language = "JavaScript">
Function displayonlineperson () {// display the number of online users
$ ("# Main. Left. Main"). Empty ();
// Asynchronous refresh (the later date parameter is mainly used to clear the JQ cache. To avoid the built-in cache of JQ, The hander/onlinehandler. ashx is mistaken for the same request)
// The returned data is a JSON string.
$. Get ("hander/onlinehandler. ashx? Date = "+ new date (), function (data ){
VaR S = 'var JSON = '+ Data + ';';
Eval (s );
$ ("# Online span"). Text (JSON. Count );
$. Each (JSON. DIC, function (I, item ){
VaR html = "<Div id = \" "+ item. ID + "\"> <span> "+ item. name + "</span> </div> ";
$ ("# Main. Left. Main"). append (HTML );
});

$ (Funcition () {// code executed when page loading is complete
Displayonlineperson (); // display the total number of online users at a time on the incoming page

Setinterval (function (){
Displayonlineperson ();
}, 3000); // It is executed every three seconds.

});
}
</SCRIPT>

4. hander/onlinehandler. ashx
<% @ Webhandler Language = "C #" class = "onlinehandler" %>

Using system;
Using system. Web;
Using model. entitise;
Using system. Collections. Generic;
Using system. Web. sessionstate; // namespace where the irequiressessionstate interface is located, implements the irequiressessionstate empty interface, mainly to indicate available sessions for handler, because Handler

The session is unavailable.
Using BLL;
Public class onlinehandler: ihttphandler, irequiressessionstate {

Public void processrequest (httpcontext context ){
Context. response. contenttype = "text/plain ";
User user = context. session ["user"] As user; // obtain the user object in the session
User. lasttime = datetime. Now; // update the Last login time of the current user
Usermanager. Update (User); // update to database
String JSON = jsonconvert. getjsonforonline (usermanager. getonlineperson (); // search for all online users
Context. response. Write (JSON );
}

Public bool isreusable {
Get {
Return false;
}
}

}

5. All online user methods, that is, the lasttime field used to query the user (User table) in the database, are less than 3 seconds earlier than the current time.
Public static ilist <user> getonlineperson (){
Using (isession session = dbhelp. sessionfactory. opensession ())
{
String SQL = "from user a where a. lasttime>: lasttime ";
Iquery iq = session. createquery (SQL );
IQ. setdatetime ("lasttime", datetime. Now. addseconds (-3 ));
Return IQ. List <user> ();
}

}

The overall idea is in index. in aspx, the current time is updated to the lasttime field of the current user every three seconds, and then the data of the lasttime field within the current time-3 is read from the database,
It is online, because the last online time of the update cannot be sent after the user exits.

Of course, this is not a timely cleaning of offline users, but the delay is 3 seconds compared with the session delay of 20 minutes. I think how can you choose? Of course, if your server is awesome, you can set a smaller value in 3 seconds...

 

 

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.