通過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="登錄" /> <asp:Button ID="btnExit" runat="server" Font-Size="9pt" OnClick="btnExit_Click" Text="退出" /> </td> </tr> <tr> <td class="style7"> </td> <td colspan="2"> </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截圖: