.NET 实现在线人数统计功能代码实例

时间:2015/12/3 16:54:00来源:互联网 作者:flyso 点击: 899 次

application最经典的一个方法:统计在线人数,这需要借助于我们的全局应用程序类来对登录的用户信息进行统计:

void application_start(object sender, eventargs e)
    {
        //在应用程序启动时运行的代码
        application["count"] = 0;
        system.io.filestream fs = system.io.file.open(server.mappath("count.txt"), system.io.filemode.openorcreate);
        system.io.streamreader sr = new system.io.streamreader(fs);
        application["allusers"] = convert.toint32(sr.readline());
        sr.close();
        fs.close();
    }
    
    void application_end(object sender, eventargs e)
    {
        //在应用程序关闭时运行的代码

    }
        
    void application_error(object sender, eventargs e)
    {
        //在出现未处理的错误时运行的代码

    }

    void session_start(object sender, eventargs e)
    {
        //在新会话启动时运行的代码
        application.lock();
        application["count"] = convert.toint32(application["count"]) + 1;
        application["allusers"] = convert.toint32(application["allusers"]) + 1;
        system.io.filestream fs = new system.io.filestream("count.txt", system.io.filemode.openorcreate, system.io.fileaccess.readwrite);
        system.io.streamwriter sw = new system.io.streamwriter(fs);
        sw.writeline(application["allusers"]);
        sw.close();
        fs.close();
        application.unlock();
    }
    void session_end(object sender, eventargs e)
    {
        //在会话结束时运行的代码。
        // 注意: 只有在 web.config 文件中的sessionstate 模式设置为inproc时,www.3ppt.com才会引发 session_end 事件。如果会话模式设置为 stateserver 或 sqlserver,则不会引发该事件。
        application.lock();
        application["count"] = convert.toint32(application["count"]) - 1;
        application.unlock();
    }

页面只要读出application的内容就行啦:

response.write(application["count"]+"当前人数"+"<br/>总人数:"+application["allusers"]);

Copyright © 2005 - 2016 flyso.cn. 飞搜 版权所有 鄂ICP备11002783号-3