用visual stdio 2010新建一个网站,在解决方案中添加三个web窗体,分别命名为ChatDisplay.aspx和ChatLogin.aspx和SendMessage.aspx,另外创建一个全局应用Global.asax。添加一个html页命名为Chat.htm。
上图为ChatLogin.aspx中的控件。
在chatlogin。aspx。cs后台文件中的代码:
public partial class ChatLogin : System.Web.UI.Page
{
//string[,] user = { { "张三", "12345" }, { "李四", "12345" }, { "王五", "12345" } };
protected void Page_Load(object sender, EventArgs e)
{
txtName.Focus();//焦点
}
protected void btnLogin_Click(object sender, EventArgs e)
{
//for (int i = 0; i < 3; i++)
//{
// if (txtName.Text == user[i, 0] && txtPassWord.Text == user[i, 1])
// {
// Session["user"] = user[i, 0];//将用户名存放在session中
// Response.Redirect("Chat.htm");
// }
//}
//Response.Write("<script>alert('用户名或密码错误!')</script>");
string sql = string.Format("select count(*) from loginName where userName='{0}' and passWord='{1}' ", txtName.Text.Trim(), txtPassWord.Text.Trim());
//连接数据库
SqlConnection connection = new SqlConnection();
connection.ConnectionString = "Data Source=.\\SQLExpress;Integrated Security=true;AttachDbFilename=|DataDirectory|\\Database.mdf;User Instance=true;";
SqlCommand command = new SqlCommand(sql, connection);
//打开数据库
connection.Open();
int count = (int)command.ExecuteScalar();
connection.Close();//关闭数据库
if (count > 0)
{
Session["user"] = txtName.Text;
Response.Redirect("Chat.htm");
}
else
{
Response.Write("<script>alert('你输入的信息不正确,重新输入!')</script>");
txtName.Text = "";
txtPassWord.Text = "";
}
}
上面的代码是利用数据库的windows验证进行查询是否有该用户,如果有该用户着跳到另一个页面中
上图为ChatDisplay.aspx中的控件,只有一个label控件用来显示说话的内容。
chatdisplay.aspx.cs后台代码:
public partial class ChatDisplay : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblMsg.Text = Application["Message"].ToString();
//lblName.Text = "发言人:"+Session["User"].ToString();
//if (!IsPostBack)
//{
// //Application["Message"] += Session["User"].ToString() + "进入聊天室-";
//}
}
}
接着
上图为sendmessage.aspx中的控件
在sendmessage.aspx.cs后台文件的代码为:
public partial class SendMessage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblName.Text = "发言人:" + Session["User"].ToString();
if (!IsPostBack)
{
Application["Message"] += Session["User"].ToString() + "进入聊天室-";
}
}
protected void btnSend_Click(object sender, EventArgs e)
{
Application.Lock();
Application["Message"] += Session["User"].ToString() + "说 " + txtMessage.Text + "(" + DateTime.Now.ToString() + ")<br/>";
Application.UnLock();
txtMessage.Text = "";
}
}
最后就是将chatlogin.aspx页面和ChatDisplay.aspx页面显示在创建的html页Chat.htm中
即Chat。htm中的代码为
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<html>
<head>
<title>我的聊天室</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
</head>
<frameset rows="20%,25%">
<frame name="top" src="ChatDisplay.aspx"></frame>
<frame name="bottom" src="SendMessage.aspx"></frame>
</frameset>
</html>
该网页聊天应用就大功告成了。
可以到我的资源里面找到这段代码源文件。