015. asp.net实现简易聊天室

通过Application和Session来实现简单的聊天室和在线用户数统计

Global.asax代码:

<%@ Application Language="C#" %>

<script runat="server">

    void Application_Start(object sender, EventArgs e) 
    {
        Application["count"] = 0;
        // 在应用程序启动时运行的代码
        //建立用户列表
        string user = "";//用户列表
        Application["user"] = user;
        Application["userNum"] = 0;//用户数
        string chats = "";//聊天记录  
        Application["chats"] = chats;
        //当前的聊天记录数
        Application["current"] = 0;
    }
    
    void Application_End(object sender, EventArgs e) 
    {
        //  在应用程序关闭时运行的代码
        Application["user"] = "";
        Application["chats"] = "";

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

    }

    void Session_Start(object sender, EventArgs e)
    {
        //在新会话启动时运行的代码
        Application.Lock();
        Application["count"] = (int)Application["count"] + 1;
        Application.UnLock();

    }

    void Session_End(object sender, EventArgs e)
    {
        //在会话结束时运行的代码。 
        // 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为
        // InProc 时,才会引发 Session_End 事件。如果会话模式 
        //设置为 StateServer 或 SQLServer,则不会引发该事件。
        Application.Lock();
        Application["count"] = (int)Application["count"] - 1;
        Application.UnLock();
    }
       
</script>

web.config代码:

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0"/>
    <sessionState mode="InProc"></sessionState>
  </system.web>

  
</configuration>

Login.aspx代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>登录</title>
    <style type="text/css">
        .style1
        {
            width: 377px;
            height: 209px;
        }
        .style2
        {
            width: 89%;
            height: 162px;
        }
        .style3
        {
            height: 29px;
        }
        .style4
        {
            height: 39px;
        }
        .style5
        {
            height: 39px;
            width: 103px;
        }
        .style6
        {
            height: 29px;
            width: 103px;
            text-align: right;
        }
        .style7
        {
            width: 103px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    <asp:Label ID="lblCount" runat="server" Text="Label"></asp:Label>
<table align="center" cellpadding="0" cellspacing="0" class="style1" >
    <tr>
        <td>
            <table align="center" cellpadding="0" cellspacing="0" class="style2">
                <tr>
                    <td class="style5">
                    </td>
                    <td class="style4" colspan="2">
                    </td>
                </tr>
                <tr>
                    <td class="style6">
                        昵称:</td>
                            <td class="style3">
                    <asp:TextBox ID="TextBox1" runat="server" Width="113px"></asp:TextBox>
                            </td>
                            <td class="style3">
                    <asp:Button ID="btnLogin" runat="server" Font-Size="9pt" OnClick="btnLogin_Click"
                        Text="登录" />
                    &nbsp;
                    <asp:Button ID="btnExit" runat="server" Font-Size="9pt" OnClick="btnExit_Click" Text="退出" />
                            </td>
                        </tr>
                        <tr>
                            <td class="style7">
                                &nbsp;</td>
                            <td colspan="2">
                                &nbsp;</td>
                        </tr>
                    </table>
                </td>
    </tr>
</table>
    </form>
</body>
</html>

Login.aspx.cs代码:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        lblCount.Text = "您是第" + Application["count"].ToString() + "位访客";//网站人数统计

        int P_int_judge = 0;
        P_int_judge = Convert.ToInt32(Request["value"]); //value的值就是P_int_judge的值
        if (!IsPostBack) //IsPostBack 获取一个值,该值指示页是第一次呈现还是为了响应回发而加载
        {
            if (P_int_judge == 1)
                Response.Write("<script>alert('该用户已经登录!')</script>");
        }
    }
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        Application.Lock();
        int P_int_num;     //在线人数
        string P_str_name; //登录用户
        string P_str_names;  //已在线的用户名
        string[] P_str_user; //用户在线数组
        P_int_num = int.Parse(Application["userNum"].ToString());
        if (TextBox1.Text == "")
        {
            Response.Write("<script>alert('用户名不能为空')</script>");
            TextBox1.Focus();
        }
        else
        {
            P_str_name = TextBox1.Text.Trim();
            P_str_names = Application["user"].ToString();
            P_str_user = P_str_names.Split(',');
            for (int i = 0; i <= P_int_num - 1; i++)
            {
                if (P_str_name == P_str_user[i].Trim())
                {
                    int P_int_judge = 1;
                    Response.Redirect("Login.aspx?value=" + P_int_judge);                
                }
            }
            if (P_int_num == 0)
                Application["user"] = P_str_name.ToString();
            else
                Application["user"] = Application["user"] + "," + P_str_name.ToString();
            P_int_num += 1;
            Application["userNum"] = P_int_num;
            Session["userName"] = TextBox1.Text.Trim();
            Application.UnLock();
            Response.Redirect("Chat.aspx");
        }
    }
    protected void btnExit_Click(object sender, EventArgs e)
    {
        Page.ClientScript.RegisterStartupScript(GetType(),"", "<script>window.opener=null;window.open('','_self');window.close();closeCurrentWindow</script>",true);
    }
}

chat.aspx代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Chat.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>无标题页</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
    </div>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <asp:ListBox ID="lbList" runat="server" Height="345px" Width="180px"></asp:ListBox> <asp:TextBox ID="txtContent" runat="server" Height="345px" TextMode="MultiLine" Width="380px"></asp:TextBox>
            <br />
            <asp:Timer ID="Timer1" runat="server" Interval="1000" ontick="Timer1_Tick">
            </asp:Timer>
            
        </ContentTemplate>
    </asp:UpdatePanel>
    <asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <asp:TextBox ID="txtMessage" runat="server" Width="316px"></asp:TextBox>
            <asp:Button ID="btnSend" runat="server" onClick="btnSend_Click" Text="发送" />
            <asp:Button ID="btnExit" runat="server"   
                Text="退出" onclick="btnExit_Click" />
        </ContentTemplate>
    </asp:UpdatePanel>
    </form>
</body>
</html>

Chat.aspx.cs代码:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Timer1_Tick(object sender, EventArgs e)
    {
        txtContent.Text = "";
        int P_int_current = Convert.ToInt32(Application["current"]); //current当前聊天记录的总数
        ArrayList ItemList = new ArrayList();
        Application.Lock();
        string P_str_names;       //已在线的用户名
        string[] P_str_user;        //用户在线数组
        int P_int_num = Convert.ToInt32(Application["userNum"]);
        P_str_names = Application["user"].ToString();//用户名, 其实是一个以 ,  分割的字符串的组织形式
        P_str_user = P_str_names.Split(',');
        for (int i = (P_int_num - 1); i >= 0; i--)
        {
            if (P_str_user[i].ToString() != "")
                ItemList.Add(P_str_user[i].ToString());
        }
        lbList.DataSource = ItemList;
        lbList.DataBind(); //绑定用户名
        string P_str_chats = Application["chats"].ToString();
        string[] P_str_chat = P_str_chats.Split(',');
        //往文本框中写入聊天记录
        for (int i = P_str_chat.Length - 1; i >= 0; i--)
        {
            if (P_int_current == 0)
            {
                txtContent.Text = P_str_chat[i].ToString();
            }
            else
            {
                txtContent.Text = txtContent.Text + "\n" + P_str_chat[i].ToString();
            }
        }
        Application.UnLock();
        UpdatePanel1.Update(); //UpdatePanel用来实现局部更新
    }
    protected void btnSend_Click(object sender, EventArgs e)
    {
        if (Session["userName"] == null || Session["userName"].ToString().Length<=0)
        {
            return;
        }
        int P_int_current = Convert.ToInt32(Application["current"]);
        Application.Lock();
        if (P_int_current == 0 || P_int_current > 20)
        {
            P_int_current = 0;
            Application["chats"] = Session["userName"].ToString() + "说:" + txtMessage.Text.Trim() + "(" + DateTime.Now.ToString() + ")";
        }
        else
        {
            Application["chats"] = Application["chats"].ToString() + "," + Session["userName"].ToString() + "说:" + txtMessage.Text.Trim() + "(" + DateTime.Now.ToString() + ")";
        }
        P_int_current += 1;
        Application["current"] = P_int_current;
        Application.UnLock();
        UpdatePanel2.Update();//更新局部面板
    }
    protected void btnExit_Click(object sender, EventArgs e)
    {
        Application.Lock();
        string P_str_userName = Application["user"].ToString();
        Application["user"] = P_str_userName.Replace(Session["userName"].ToString(), "");
        Session["userName"] = ""; //清空session
        string astr = Application["user"].ToString();
        Application.UnLock();
        Response.Redirect("Login.aspx");//退出后转到登录界面
    }
}

 Login.aspx截图:

Chat.aspx截图:

posted on 2016-12-06 13:28  印子  阅读(2178)  评论(1编辑  收藏  举报

导航