How does. Net count online users?

Source: Internet
Author: User
Tags connectionstrings

The purpose of online user statistics is self-evident that website administrators can know the number of current users and observe the performance of servers or programs based on the number of users, so that we 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, this method makes 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" %>
<Html>
<Head>
<Script language = "c #" RUNAT = "server">
Private void Page_Load (object sender, System. EventArgs e)
{
Visitors. Text = "this site currently has: <B>" + Application ["user_sessions"]. ToString () + "" + "</B> Visitors! ";
}
<Title> online users </title>
</Head>
<Body>
<Asp: label "runat =" server "/> <br>
</Body>
</Html>

It can be seen that the above program is very simple, that is, to call the Application, of course, we do not need to design a page to display the number of online users, in any page of the website, we can call Application ("user_sessions") directly "). 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:

<Script language = "c #" runat = "Server">
Protected void Application_Start (Object sender, EventArgs e)
{
Application ["user_sessions"] = 0;
}
Protected void Session_Start (Object sender, EventArgs e)
{
Application. Lock ();
Application ["user_sessions"] = (int) Application ["user_sessions"] + 1;
Application. Unlock ();
}
Protected void Session_End (Object sender, EventArgs e)
{
Application. Lock ();
Application ["user_sessions"] = (int) Application ["user_sessions"]-1;
Application. Unlock ();
}
</Script>

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 ") in this way, the statistics of online users are cleverly implemented.

Trinity Discussion

The above statistics are concise and concise, and the program is easy to implement. However, if we think carefully, we find that this method has certain limitations, the number of online users calculated may be slightly different because 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 and enters another website, the session will not end in a certain period of time, which can be set through TimeOut. Generally, we set it to 20 minutes. Therefore, there is still a slight error in the user count statistics.

In addition, we know that in ASP, if the user sets the Cookies on the browser to disabled, the Session will no longer be passed. Obviously, this setting makes the above statistical program powerless, in ASP. NET. in the web file, we can set <sessionstate cookieless = "false"/> to true, that is, the Session can be passed without using Cookies, our programs can run smoothly in different visitor environments.

Preparations
1. Create a database for TongJi and add a table for tongji. There is a Number field in the table, which is of the int type. The initial value of Numger is 1000;
2. Create a website;
3. Create a database connection string (specific method) and save it to the Web. config file. The code in the <connectionString> section is as follows:

<ConnectionStrings>
<Add name = "TongJiConnectionString" connectionString = "Data Source =.; Initial Catalog = TongJi; Integrated Security = True" providerName = "System. Data. SqlClient"/>
</ConnectionStrings>

Key code
4. Add a new project/Global application class: Global. asax. The code for the file is as follows:

<% @ Application Language = "C #" %>
<% @ Import Namespace = "System. Data. SqlClient" %>

<Script runat = "server">

Void Application_Start (object sender, EventArgs e)
{
// Code that runs when the application starts
SqlConnection con = new SqlConnection ();
Con. ConnectionString = ConfigurationManager. ConnectionStrings ["TongJiConnectionString"]. ConnectionString;
Con. Open ();
SqlCommand cmd = new SqlCommand ("select * from tongji", con );
Int count = Convert. ToInt32 (cmd. ExecuteScalar ());
Con. Close ();
Application ["total"] = count;
Application ["online"] = 0;
}

Void Application_End (object sender, EventArgs e)
{
// Code that runs when the application is closed
SqlConnection con = new SqlConnection ();
Con. ConnectionString = ConfigurationManager. ConnectionStrings ["TongJiConnectionString"]. ConnectionString;
Con. Open ();
SqlCommand cmd = new SqlCommand ("update tongji set Number =" + Application ["total"]. ToString (), con );
Cmd. ExecuteNonQuery ();
Con. Close ();
}

Void Application_Error (object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}

Void Session_Start (object sender, EventArgs e)
{
// The code that runs when the new session starts
Application. Lock ();
Application ["total"] = (int) Application ["total"] + 1;
Application ["online"] = (int) Application ["online"] + 1;
Application. UnLock ();
}

Void Session_End (object sender, EventArgs e)
{
// The code that runs when the session ends.
Application. Lock ();
Application ["online"] = (int) Application ["online"]-1;
Application. UnLock ();
}

</Script>

Run the test
5. Drag two labels to Default. ASPx;
6. Its Default. ASPx. cs code is as follows:

Public partial class _ Default: System. Web. UI. Page
{
Protected void Page_Load (object sender, EventArgs e)
{
This. Label1.Text = "total Number of visitors" + Application ["total"]. ToString ();
This. Label2.Text = "Current online quantity" + Application ["online"]. ToString ();
}
}

7. OK !! Start debugging.

Notes

8,
During debugging in VS2005, the total number of visitors is 1001; currently, the number of online users is 1;
I re-open another IE and Copy the address to it. The total number of visitors is 1002, and the current number of online users is 2;
This means everything is normal. But it is still 1000 in the database ,??????
I am here to delay a lot of time (one day), but in my despair, I tried again,
This time, however, God gave me an unexpected gift.

In VS2005, select "save Global" from the "file" menu ";
In this case, the value 1000 in the database is updated to 1002.
If the same is true for I S debugging, you must shut down or stop the WWW Service before writing data into the database.

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.