weiconfig:
<system.web>
<httpHandlers>
<add path="comet_broadcast.ashx" type="AsnyHandler" verb="POST,GET"/>
</httpHandlers>
<compilation debug="true" targetFramework="4.0"/>
<httpRuntime/>
</system.web>
一般处理程序Handler1:
public class Handler1 : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World:" + DateTime.Now.ToString("HH:mm:ss"));//需要输出特定的信息的,可以在这里处理,例如读取数据库的最新参数啊,获取memcached的值之类的都行.
} public bool IsReusable
{
get
{
return false;
}
}
}
页面:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<style type="text/css">
* {
font-size: 12px;
} #divResult {
border: 1px solid #;
width: 250px;
}
</style>
<script src="Scripts/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
function fUpdateData(data) { $.post("comet_broadcast.ashx", { content: data },
function (data, status) {
alert(data);
var result = $("#divResult");
result.html(result.html() + "<br/>" + data);
// $("#divResult").html(data);
//服务器返回消息,再次请求后台数据
fGetData();
}, "html"
);
}
//获取服务器最新信息
function fGetData() {
$.ajax({
type: 'GET',
url: 'Handler1.ashx',
success: function (data) { fUpdateData(data);
}
});
}
$(document).ready(function () {
//初始化
fGetData();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
后台推送最新消息:
<div id="divResult">
</div>
</div>
</form>
</body>
</html>
AsnyHandler类与 myAsynResult类:
public class AsnyHandler:IHttpAsyncHandler
{
public AsnyHandler()
{
} public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
{
//myAsynResult为实现了IAsyncResult接口的类,当不调用cb的回调函数时,该请求不会返回到给客户端,会一直处于连接状态
myAsynResult asyncResult = new myAsynResult(context, cb, extraData);
String content = context.Request.Params["content"]; //向Message类中添加该消息
Messages.Instance().AddMessage(content, asyncResult);
return asyncResult;
} #region 不必理会 public void EndProcessRequest(IAsyncResult result)
{ } public bool IsReusable
{
get { return false; ; }
} public void ProcessRequest(HttpContext context)
{
}
#endregion
}
public class myAsynResult : IAsyncResult
{
bool _IsCompleted = false;
private HttpContext context;
private AsyncCallback cb;
private object extraData;
public myAsynResult(HttpContext context, AsyncCallback cb, object extraData)
{
this.context = context;
this.cb = cb;
this.extraData = extraData;
}
private string _content;
public string Content {
get {return _content;}
set{_content=value;}
} #region IAsyncResult接口
public object AsyncState
{
get { return null; }
} public System.Threading.WaitHandle AsyncWaitHandle
{
get { return null; }
} public bool CompletedSynchronously
{
get { return false; }
}
public bool IsCompleted
{
get { return _IsCompleted; }
}
#endregion //在Message类中的添加消息方法中,调用该方法,将消息输入到客户端,从而实现广播的功能
public void Send(object data)
{
context.Response.Write(this.Content);
if (cb!=null)
{
cb(this);
}
_IsCompleted = true; ;
}
}
Messages类:
public class Messages
{
//记录所有请求的客户端
List<myAsynResult> clients = new List<myAsynResult>(); #region 实现该类的单例
private static readonly Messages _Instance = new Messages();
private Messages()
{
}
public static Messages Instance()
{
return _Instance;
}
#endregion public void AddMessage(string content,myAsynResult asyncResult)
{
//当传入的内容为"-1"时,表示为建立连接请求,即为了维持一个从客户端到服务器的连接而建立的连接
//此时将该连接保存到 List<myAsynResult> clients中,待再有消息发送过来时,该连接将会被遍历,并且会将该连接输出内容后,结束该连接
if (content=="-1")
{
clients.Add(asyncResult);
}
else
{
//将当前请求的内容输出到客户端
asyncResult.Content = content;
asyncResult.Send(null); //否则将遍历所有已缓存的client,并将当前内容输出到客户端
foreach (myAsynResult result in clients)
{
result.Content = content;
result.Send(null);
} //清空所有缓存
clients.Clear();
}
}
}