weiconfig:
12 3 54 6 7
一般处理程序Handler1:
1 public class Handler1 : IHttpHandler 2 { 3 4 public void ProcessRequest(HttpContext context) 5 { 6 context.Response.ContentType = "text/plain"; 7 context.Response.Write("Hello World:" + DateTime.Now.ToString("HH:mm:ss"));//需要输出特定的信息的,可以在这里处理,例如读取数据库的最新参数啊,获取memcached的值之类的都行. 8 } 9 10 public bool IsReusable11 {12 get13 {14 return false;15 }16 }17 }
页面:
1 2 3 455 565 15 16 46 47 48
AsnyHandler类与 myAsynResult类:
1 public class AsnyHandler:IHttpAsyncHandler 2 { 3 public AsnyHandler() 4 { 5 } 6 7 public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData) 8 { 9 //myAsynResult为实现了IAsyncResult接口的类,当不调用cb的回调函数时,该请求不会返回到给客户端,会一直处于连接状态10 myAsynResult asyncResult = new myAsynResult(context, cb, extraData);11 String content = context.Request.Params["content"];12 13 //向Message类中添加该消息14 Messages.Instance().AddMessage(content, asyncResult);15 return asyncResult;16 }17 18 #region 不必理会19 20 public void EndProcessRequest(IAsyncResult result)21 {22 23 }24 25 public bool IsReusable26 {27 get { return false; ; }28 }29 30 public void ProcessRequest(HttpContext context)31 {32 }33 #endregion34 }35 public class myAsynResult : IAsyncResult36 {37 bool _IsCompleted = false;38 private HttpContext context;39 private AsyncCallback cb;40 private object extraData;41 public myAsynResult(HttpContext context, AsyncCallback cb, object extraData)42 {43 this.context = context;44 this.cb = cb;45 this.extraData = extraData;46 }47 private string _content;48 public string Content { 49 get { return _content;}50 set{_content=value;} 51 }52 53 #region IAsyncResult接口54 public object AsyncState55 {56 get { return null; }57 }58 59 public System.Threading.WaitHandle AsyncWaitHandle60 {61 get { return null; }62 }63 64 public bool CompletedSynchronously65 {66 get { return false; }67 }68 public bool IsCompleted69 {70 get { return _IsCompleted; }71 }72 #endregion73 74 //在Message类中的添加消息方法中,调用该方法,将消息输入到客户端,从而实现广播的功能75 public void Send(object data)76 {77 context.Response.Write(this.Content);78 if (cb!=null)79 {80 cb(this);81 }82 _IsCompleted = true; ;83 }84 }
Messages类:
1 public class Messages 2 { 3 //记录所有请求的客户端 4 Listclients = new List (); 5 6 #region 实现该类的单例 7 private static readonly Messages _Instance = new Messages(); 8 private Messages() 9 {10 }11 public static Messages Instance()12 {13 return _Instance;14 }15 #endregion16 17 public void AddMessage(string content,myAsynResult asyncResult)18 {19 //当传入的内容为"-1"时,表示为建立连接请求,即为了维持一个从客户端到服务器的连接而建立的连接20 //此时将该连接保存到 List clients中,待再有消息发送过来时,该连接将会被遍历,并且会将该连接输出内容后,结束该连接21 if (content=="-1")22 {23 clients.Add(asyncResult);24 }25 else26 {27 //将当前请求的内容输出到客户端28 asyncResult.Content = content;29 asyncResult.Send(null);30 31 //否则将遍历所有已缓存的client,并将当前内容输出到客户端32 foreach (myAsynResult result in clients)33 {34 result.Content = content;35 result.Send(null);36 }37 38 //清空所有缓存39 clients.Clear();40 }41 }42 }