日期:2014-05-18 浏览次数:20588 次
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <style> *{ font-size:12px;} #divResult { border:1px solid #000; width:250px; } </style> <script src="Scripts/jquery-1.3.2.min.js" type="text/javascript"></script> <script src="Scripts/myJS.js" type="text/javascript"></script> </head> <body> 广播内容: <input type="text" id="content" /><br /> 消息记录: <div id="divResult"></div> <input type="button" id="btnSend" value="广播" /> </body> </html>
using System; using System.Collections.Generic; using System.Web; using System.Threading; /// <summary> /// Summary description for AsnyHandler /// </summary> 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; ; } }
using System; using System.Collections.Generic; using System.Web; /// <summary> /// Summary description for Messages /// </summary> public class Messages { //记录所有请求的客户端 List<myAsynResult> clients = new List<myAsynResult>(); #region 实现该类的单例 private static readonly Messages _Instance = new Messages(); private Messages() { } public static M