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 id = "visitors" runat = "server"/> <br>
</Body>
</Html> we can see that the preceding Program It is particularly simple 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
The role of the global. asax file does not have to be said. 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>
Above Code It is easy to understand that 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) lock the application, and then add application ("user_sessions"). When the user exits the website, the application ("user_sessions") is reduced by 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.
Iv. Summary
The above statistical procedures are very simple, but we do not necessarily think of details. This is what we need to consider more in programming.