ASP.NET网站聊天室的设计与实现(第3节) |
本文标签:ASP.NET,网站聊天室 大家都玩过网站聊天室吧,那知道它是怎么实现的吗? public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Application["user_online"] == null) { Application["user_online"] = 0; } Application["user_online"] = (int)Application["user_online"] + 1; Label3.Text = "(现在共有" + Application["user_online"].ToString() + "人在线!)"; } protected void Button1_Click(object sender, EventArgs e) { if (Page.IsPostBack) { Session["User_name"]=this.Txt1.Text; Response.Redirect("chat.aspx"); } } } 第二步,构建登录字符串与发言字符串 protected void Page_Load(object sender, EventArgs e) { string user_name = (string)Session["user_name"]; string sayStr = "来自" + (string)Request.ServerVariables["REMOTE_ADDR"] + "的"; sayStr = sayStr + "<b><font color=red>" + user_name + "</font></b>"; sayStr = sayStr + "于" + DateTime.Now + "大驾光临"; Application.Lock(); Application["show"] = sayStr + "<br>" + Application["show"];I=I+1 Application.UnLock(); } 3、构建发言内容字符串 。创建输入发言内容的页面文件Inputwin.aspx 。为页面Inputwin.aspx添加控件,这里使用两个DropDownList下拉列表框控件,分别用来选择发言人的性别和心情,一个单行Textbox控件(对谁说);一个多行Textbox控件(发言内容);一个Button按钮(发言按钮),最后添加验证控件 。 protected void Button1_Click(object sender, EventArgs e) { if (Page.IsPostBack == true) //页面数据回传 { String ssex, emotion, who; ssex = DropDownList1.SelectedItem.Value; //获取性别 emotion = DropDownList2.SelectedItem.Text + "的"; //获取发言时表情 who = "对" + "<b>" + TextBox2.Text + "</b>"; //获取对谁说 //构建发言字符串: String sayStr = "<font size=3 color=00ff00><b>" + (string)Session["user_name"]; sayStr = sayStr + ssex + "</b></font>在" + DateTime.Now + emotion + who + " 说:"; sayStr = sayStr + TextBox3.Text; Application.Lock(); Application["show"] = sayStr + "<br>" + (string)Application["show"]; Application.UnLock(); TextBox3.Text = "";// 将发言框清空 } } 4、创建显示发言字符串和发言内容的页面文件(Showwin.aspx),实现代码如下: <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>无标题页</title> <meta http-equiv="refresh" content="4"/> </head> <body> <form id="form1" runat="server"> <div> </div> </form> </body> </html> 在Showwin.aspx.cs的Page_Load事件中编写代码如下: public partial class showwin : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Response.Write((string)Application["show"]); } } 5、为离开聊天室页面的Exit.aspx.cs文件编写代码如下: protected void Page_Load(object sender, EventArgs e) { string sayStr = "<b>" + (string)Session["user_name"] + "</b>"; sayStr = sayStr + "于" + DateTime.Now + "离开聊天室了"; sayStr = "<font color=green>" + sayStr + "</font>"; Application.Lock(); Application["show"] = sayStr + "<br>" + (string)Application["show"]; Application["user_online"] = (int)Application["user_online"] - 1; Application.UnLock(); Response.Redirect("chatroom.aspx"); } 6、运行聊天室首页Default.aspx 。 运行效果图 总结 |