asp.net 統計顯示線上訪問人數程式碼

來源:互聯網
上載者:User

線上使用者訪問人數,也就是說,要為網站寫一個計數器,計數器的初始值為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有使用了兩個瀏覽器,這樣是為了讓網站擷取不同的進程訪問者。而每個瀏覽器開啟不同的視窗,所獲得到的資料變數。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.