开发分布式WebIm--3(Comet模型)
原文是:http://www.codeproject.com/KB/aspnet/CometAsync.aspx
Asp.net环境下实现Comet就要用到 IHttpAsyncHandler接口
并实现其中的BeginProcessRequest和EndProcessRequest方法
BeginProcessRequest方法中的HttpContext包含了Response和Request对象,AsyncCallback用于异步调用结束,运行结束后需要返回一个IAsyncResult对象。
我在BeginProcessRequest函数中通过Request获取了一个名为ElementData的JSon字符串,并通过Element解析出用户名和在线状态。
CometAsyncResult构造函数只是简单的保存了HttpContext、AsyncCallback这两个对象,AddCometAsyncResult函数则实现了根据用户名获取全网中的留言信息、复制好友列表到聊天服务器、好友状态交换等业务逻辑。当然还有一点最为关键的,就是把用户名和HttpContext、AsyncCallback这两个对象对应起来,这样才能通过用户名来发送消息。当你完成这一切的时候,Comet模型就建立起来了,非常的简单。根据我测试windows2003+IIS6.0环境下可以同时4000-8000个链接,windows2008+IIS7.0环境下可达到15000个链接。
using System.Data;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Threading;
using System.Web;
using PCBaseLib.Entity;
using CometAsync.Remoting;
namespace CometAsync.Comet
{
public class CometAsyncHandler : IHttpAsyncHandler
{
#region IHttpAsyncHandler Members
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
{
//保存状态
CometAsyncResult result = new CometAsyncResult(context.Response, cb, extraData);
Element Ele=null;
if (context.Request.Form["ElementData"] != null)
Ele = new Element(context.Request.Form["ElementData"], true);
else
{
Ele = new Element("test");
Ele["From"] = "user" + HttpContextRemoting.UsersOnline.Count.ToString();
Ele["State"] = "0";
}
result.AddCometAsyncResult(Ele["From"], Ele["State"]);
// ok, return it
return result;
}
public void EndProcessRequest(IAsyncResult result)
{
}
#endregion
#region IHttpHandler Members
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
throw new InvalidOperationException("ASP.NET Should never use this property");
}
#endregion
}
}
运行上述代码,请在web.config文件中加入httpHandlers节,注册访问页由你的类来处理,如下CometLink.ashx的处理函数、命名空间全名为:CometAsync.Comet.CometAsyncHandler
<add verb="GET, POST" path="CometLink.ashx" type="CometAsync.Comet.CometAsyncHandler, CometAsync" validate="false"/>
<add verb="GET, POST" path="SendMessage.ashx" type="CometAsync.IM_Command.SendMessage, CometAsync" validate="false"/>
<add verb="GET, POST" path="Join.ashx" type="CometAsync.IM_Command.Join, CometAsync" validate="false"/>
<add verb="GET, POST" path="Agree.ashx" type="CometAsync.IM_Command.Agree, CometAsync" validate="false"/>
<add verb="GET, POST" path="Login.ashx" type="CometAsync.IM_Command.Login, CometAsync" validate="false"/>
<add verb="GET, POST" path="Refuse.ashx" type="CometAsync.IM_Command.Refuse, CometAsync" validate="false"/>
<add verb="GET, POST" path="Presence.ashx" type="CometAsync.IM_Command.Presence, CometAsync" validate="false"/>
<add verb="GET, POST" path="PresenceEx.ashx" type="CometAsync.IM_Command.PresenceEx, CometAsync" validate="false"/>
<add verb="GET, POST" path="InfoSet.ashx" type="CometAsync.IM_Command.InfoSet, CometAsync" validate="false"/>
</httpHandlers>