Count online users

Source: Internet
Author: User

Original: http://community.csdn.net/Expert/topic/3835/3835032.xml? Temp =. 1909601.
Thanks: afritxia (difficult to live)

When a user accesses a website, a sessionid is assigned to the user. Create a one-to-one correspondence between the IP address and the user name. If the user opens a new window, check whether the user's IP address or user name has already appeared in onlineusershash? If yes, point the new sessionid to the existing IP address. When a session ends, the sessionid is removed from onlineusers_sessioniphash. Determine whether there are other sessionids pointing to this IP address. If not, remove the user name from the online user list. The client situation is quite complex and must be fully considered. The following is the newAlgorithmOfCode:

// In the global. asax. CS File
//
// Primary key name of the online user list
Public const string key_onlineusers = "onlineusers ";
// Primary key name of the session table in the online user list
Public const string key_onlineusers_sessionip = "onlineusers_sessionip ";

Protected void application_start (Object sender, eventargs E)
{
Application. Lock ();

Application [key_onlineusers] = NULL;
Application [key_onlineusers_sessionip] = NULL; // the user's sessionid corresponds to the IP address.

Application. Unlock ();
}

Protected void session_start (Object sender, eventargs E)
{
Application. Lock ();

/*...*/

Hashtable onlineusershash = (hashtable) application [key_onlineusers];
Hashtable onlineuserssessioniphash = (hashtable) application [key_onlineusers_sessionip];

If (visitor. current. isguest) // if the user is a guest
{< br> If (onlineusershash. containskey (request. userhostaddress)
{< br> onlineusershash [request. userhostaddress] = "";
}< br> else
{< br> onlineusershash. add (request. userhostaddress, "");
}< BR >}< br> else
{< br> If (! Onlineusershash. containskey (request. userhostaddress)
&&! Onlineusershash. containsvalue (visitor. current. username)
{< br> // if the user's IP address and user name cannot be found in the list,
onlineusershash will be added to the online user list. add (request. userhostaddress, request. cookies ["username"]. value);
}< br> else if (onlineusershash. containsvalue (request. cookies ["username"]. value)
{< br> // if the user's cookie information can be found, update (delete and then add) IP address of an online user
// Description: The user may have logged on to the system shortly after the logon due to a line failure, disconnect and dial again
// when the user returns to the website, the cookie has not expired, but the IP address has changed
string username = request. cookies ["username"]. value;

Foreach (Object key in onlineusershash. Keys)
{
If (string) onlineusershash [Key]). Equals (username ))
{
// Delete the IP address that the user just used
Onlineusershash. Remove (key );
Break;
}
}

// Add an online user
Onlineusershash. Add (request. userhostaddress, request. Cookies ["username"]. value );
}
Else if (onlineusershash. containskey (request. userhostaddress ))
{
// If the user's IP address can be found, the name of the online user is updated.
//
// Note: After logging on, log off and log on again. It may be to change the user name.
Onlineusershash [request. userhostaddress] = request. Cookies ["username"]. value;
}
}

// Maps the user's IP address and sessionid
If (! Onlineuserssessioniphash. containskey (session. sessionid ))
Onlineuserssessioniphash. Add (session. sessionid, request. userhostaddress );

Application. Unlock ();
}

Protected void session_end (Object sender, eventargs E)
{
Application. Lock ();

If (application [key_onlineusers]! = NULL)
{
Hashtable onlineusershash = (hashtable) application [key_onlineusers];
Hashtable onlineuserssessioniphash = (hashtable) application [key_onlineusers_sessionip];

// Obtain the user's IP address
String IP = (string) onlineuserssessioniphash [session. sessionid];

// Remove the user's IP address
Onlineuserssessioniphash. Remove (session. sessionid );

// If no session points to this IP address, it indicates that the user has indeed left the website.
// The user name can be deleted.
If (! Onlineuserssessioniphash. containsvalue (IP ))
Onlineusershash. Remove (IP );
}

Application. Unlock ();
}

Bytes ----------------------------------------------------------------------------------------

It is self-evident to count online users so that website managers can know the number of current users, and then observe the server orProgramSo that you can intuitively understand the attractiveness of the website or the efficiency of the website program. Now, we will introduce a simple and clear method to count the number of online users. The feature of this method is to make full use of ASP. net, combined with global. the asax file uses application and session to skillfully implement online user statistics. Because only one application is used in the program, the system resources occupied by the program can be ignored. Of course, this is also one of the top concerns of website administrators.

1. Use of the User display page

First, let's take a look at how the current number of users to access the website. The program code is as follows:

<% @ page Language = "C #" DEBUG = "true" %>


It can be seen that the above program is particularly simple, that is, to call the application. Of course, we do not need to design a page to display the number of online users. On any page of the website, we can directly call application ("user_sessions "). tostring () to display the number of current users.

II. Implementation of the global. asax File

We do not have to mention the role of the Global. asax file. Now, let's look at how to count the number of online users:

The above code is easy to understand. When the website starts to serve (when the application starts), the Program sets application ["user_sessions"] to zero. Then, when the user enters the website (when the session starts), the application is locked, and application ("user_sessions") is added. When the user exits the website, the application ("user_sessions ") minus one. In this way, the statistics of online users are cleverly implemented.

III. A little discussion

The above statistics are concise and easy to implement. However, if we carefully consider the limitations of this method, the number of online users may be slightly different. In the above program, we add or subtract the number of online users based on the user's session creation and exit. We know that if the user does not close the browser, however, when you enter another website, the session will not end in a certain period of time. We can set this time through timeout. Generally, we set this time to 20 minutes. Therefore, there is still a slight error in the user quantity statistics.

In addition, we know that in ASP, if the user sets the cookies on the browser to "disabled", the session cannot be passed. Obviously, this setting makes the above statistical program powerless. However, in ASP. net. in the Web file, we can set <sessionstate cookieless = "false"/> to true. That is to say, the session can be passed without using cookies. In this way, our programs can run smoothly in different visitor environments.
Bytes -----------------------------------------------------------------------------------------
How to display online users and locations

I. Principles
The application_authenticaterequest event and application_beginrequest event in global. asax in. NET are triggered every time the aspx file is accessed. However, in application_beginrequest, ticket tickets with froms authentication cannot be identified. Therefore, it can only be put in application_authenticaterequest.

My implementation principle is: Every time I access the aspx file, I will judge whether there is this user in the online table (the logged user name has been logged on, and the recorded IP Address has not been logged on). If it does not exist, the user's identity, last access time, last access IP address, and last access URL are stored in the database. If the database already exists, update the record to update the last access time, IP address, and last access URL.

At the same time, delete the data in the database that is more than 20 minutes away from the current time (if no operation is performed for 20 minutes, the operation times out ).

Ii. Advantages
In this way, you can not only see the exact number of people online, but also know who is online and whether to log on to the website, the proportion of the number of people who are already members, and the location where they are, calculate the number of people on a page.

Iii. database structure:
Whether the length of the primary key field type is null
1uson_serialint40 No.
0uson_uservarchar200 username (IP address if logon fails)
0uson_companyvarchar1000 company name ('tourist 'if not logged in ')
0uson_ip varchar200ip address
0uson_datedatetime80 last operation time
0uson_urlvarchar1000 path to the last operation page

4. Procedures
Note:
1. The program is located in global. asax.
2. I am using Forms authentication
3. Please use system. Web. Security

Protected void application_authenticaterequest (Object sender, eventargs E)
{
String struserid = string. empty;
String strcompany = string. empty;
If (request. isauthenticated)
{
Formsidentity identity = (formsidentity) user. identity;
Formsauthenticationticket ticket = identity. ticket;
Struserid = user. Identity. Name;
Strcompany = ticket. userdata. Split ("|". tochararray () [2];
}
Else
{
Struserid = request. userhostaddress;
Strcompany = "Tourists ";
}

Memberonlineinfo objonline = new memberonlineinfo (struserid, request. userhostaddress, datetime. Now. tostring (), request. filepath, strcompany );

Memberaccount account = new memberaccount ();
If (! Account. checkuseronline (struserid ))
Account. addonline (objonline );
Else
Account. updateonline (objonline );

// Delete the expired Member
Account. deleteonline ();
}

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.