在线用户访问人数,也就是说,要为网站写一个计数器,计数器的初始值为0,网站一开始运行时(Application_Start),就开始统计,当有用户访问时(Session_Start)计数器加1,当用户访问离开时(Session_End)计数器减1。
在程序开始时,定义一个计数器,初始值为0
代码如下 | 复制代码 |
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs) ' Code that runs on application startup Application("OnlineVisitors") = 0 End SubView Code |
当有用户访问网站时:
代码如下 | 复制代码 |
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs) ' Code that runs when a new session is started Application.Lock() Application("OnlineVisitors") = DirectCast(Application("OnlineVisitors"), Integer) + 1 Application.UnLock() End Sub |
当用户离开网站时:
代码如下 | 复制代码 |
Sub Session_End(ByVal sender As Object, ByVal e As EventArgs) ' Code that runs when a session ends. ' Note: The Session_End event is raised only when the sessionstate mode ' is set to InProc in the Web.config file. If session mode is set to StateServer ' or SQLServer, the event is not raised. Application.Lock() Application("OnlineVisitors") = DirectCast(Application("OnlineVisitors"), Integer) - 1 Application.UnLock() End Sub |
上面两个Session_Start和Session_End方法中,Insus.NET有使用Application.Lock和Application.Unlock方法,是为了防止多个线程同时改变这个变量,在变更计数器时,先把它Lock起来,更变完毕,再Unlock。
把Global.asax文件保存,在网页中需要显示网站在线访问人数的位置:
代码如下 | 复制代码 |
<%= Application("OnlineVisitors").ToString()%> |
测试测试,测试过程中,Insus.NET有使用了两个浏览器,这样是为了让网站获取不同的进程访问者。而每个浏览器打开不同的窗口,所获得到的数据变量。
时间: 2024-10-23 08:24:52