counting active visitors using global.asa only for specific page
using a code like this will count the active visitors on my website.
global.asa
Sub Application_OnStart
Application("ActiveUsers") = 0
End Sub
Sub Session_OnStart
Session.Timeout = 20
Session("Start") = Now
Application.Lock
Application("ActiveUsers") = Application("ActiveUsers") + 1
开发者_运维百科 Application.UnLock
End Sub
Sub Session_OnEnd
Application.Lock
Application("ActiveUsers") = Application("ActiveUsers") - 1
Application.UnLock
End Sub
What I need is only for a specific page - it is for a waiting list for a chat.
You can't use the global.asa
in such case.
You will have to write code in that specific page.
Increasing the visitors count is trivial: just have this code in the page:
Application.Lock
Application("ChatUsers") = Application("ChatUsers") + 1
Application.UnLock
The tricky part is to decrease the count when someone leaves the page. For this you have to use client side script and AJAX: client side script triggered in the page unload
event will send request to the server telling it that someone left the page.
Most common and simple way is by using jQuery - so such code in the .asp
should work:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
$(window).bind("unload", function() {
$.ajax({ url: "<%=Request.ServerVariables("Script_Name")%>", type: "POST", data: "visitor_has_left=true", async: false });
});
</script>
This will send the AJAX request, now to handle it have such ASP code:
<%
If Request.Form("visitor_has_left")="true" Then
If Application("ChatUsers")>0 Then
Application.Lock
Application("ChatUsers") = Application("ChatUsers") - 1
Application.UnLock
End If
Response.End()
Else
Application.Lock
Application("ChatUsers") = Application("ChatUsers") + 1
Application.UnLock
End If
%>
(It already combines the code to increase the count as well)
Just tested it now and it works, hope the concept is clear as well.
Note, I set async
to false
because of Chrome: it's smart enough to cancel the request if the document changing location right after sending the request, so waiting for response force even Chrome to send the desired request.
精彩评论