试试这个.. 样品图片 - SimpleChat.jpg 介绍
为什么不,如何创建为您的网站一个简单的聊天室吗?那么,最好的方法是使用一个漂亮的数据库来存储消息;不过,为了演示目的,我将使用静态数组。我知道,你将无法在网络农场中使用它。以这篇文章为概念,而不是解决方案。这个简单的网络聊天程序旨在支持任何浏览器。
此外,您可以选择多个聊天室。为什么不从这个渠道延伸到更多渠道? 背景
几个月前,我一直在寻找一个完整的在线客户服务ASP.NET控件,使我的生活更轻松,没有发现任何有趣的东西,所以我建立了自己的。 使用代码
如果你使用一个数据库来保存信息替换这个类: 收起
public class Chat
{
static protected ArrayList pArray = new ArrayList();
static public void AddMessage(string sDealer,
string sUser, string sMsg)
{
string sAddText = sDealer + "~" + sUser + "~" + sMsg;
pArray.Add(sAddText);
if (pArray.Count > 200)
{
pArray.RemoveRange(0,10);
}
}
static public string GetAllMessages(string sDealer)
{
string sResponse = "";
for (int i=0; i< pArray.Count; i++)
{
sResponse = sResponse +
FormatChat(pArray[i].ToString(), sDealer);
}
return(sResponse);
}
static private string FormatChat(string sLine, string sDealer)
{
int iFirst = sLine.IndexOf("~");
int iLast = sLine.LastIndexOf("~");
string sDeal = sLine.Substring(0, iFirst);
if (sDeal != sDealer)
return("");
string sUser = sLine.Substring(iFirst+1, iLast-(iFirst+1));
string sMsg = sLine.Substring(iLast+1);
string sRet = "" + sUser + ": " + sMsg + "";
return(sRet);
}
}
上面的代码读取并从静态数组在数据库中这样写。该代码只允许在该数组中有200条消息,此后它将删除前10位。
聊天页面非常简单;这是aspx.cs后面的代码: 收起
public class ChatWin : System.Web.UI.Page
{
protected System.Web.UI.WebControls.TextBox TB_ToSend;
protected System.Web.UI.WebControls.Button BT_Send;
private void Page_Load(object sender, System.EventArgs e)
{
if (Page.IsPostBack == false)
{
if (Request.Params["Channel"] != null)
Session["ChatChannel"] =
Request.Params["Channel"].ToString();
else
Session["ChatChannel"] = "1";
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <SUMMARY>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </SUMMARY>
private void InitializeComponent()
{
this.BT_Send.Click +=
new System.EventHandler(this.BT_Send_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
public string GetChatPage()
{
return("TheChatScreenWin.aspx");
}
private void BT_Send_Click(object sender, System.EventArgs e)
{
string sChannel = "";
string sUser = "";
if (Request.Params["Channel"] != null)
sChannel = Request.Params["Channel"].ToString();
else
sChannel = "1";
if (Request.Params["User"] != null)
sUser = Request.Params["User"].ToString();
else
{
Random pRan = new Random();
int iNum = pRan.Next(9);
sUser = "Annonymouse" + iNum;
}
if (TB_ToSend.Text.Length > 0)
{
PageModule.Chat.AddMessage(sChannel,
sUser,
TB_ToSend.Text);
TB_ToSend.Text = "";
}
}
}
当点击了按钮SEND时,它调用函数方法addMessage,增加了一行到静态数组的末尾。
标记内的页面每4秒刷新一次而不刷新实际页面。
在codeplex上搜索你会发现更多http://www.codeplex.com/site/search?query=chat&ac=3 – 2011-05-04 11:36:43