comet

引用自:http://blog.csdn.net/wanglipo/article/details/7256886
1.客户端请求

 

<script type="text/javascript"> 

var HttpRequest; 

function CreateXmlHttpRequest()
{
   if(window.XMLHttpRequest)
   {
      HttpRequest=new XMLHttpRequest();
   }
   else if(window.ActiveXObject)
   {
      HttpRequest=new ActiveXObject("MICROST.XMLHTTP");
   }


function Send()
{
    document.getElementById("test").innerHTML="等待返回信息";
    CreateXmlHttpRequest();
    if(HttpRequest!=null)
    {
       HttpRequest.onreadystatechange=ShowMessage;
       HttpRequest.open("GET","Handler.ashx?name="+escape("leon")+"&m"+Math.random());
       HttpRequest.send();
    }


function ShowMessage()
{
    if(HttpRequest.readyState==4&&HttpRequest.status==200)
    {
        if(HttpRequest.responseText.length>0)
        {
           alert(HttpRequest.responseText);//收到信息
           //如果有信息返回 重新发送请求 递归
           Send();
        }
    }


</script> 

2.服务的如何hold请求

 

Code
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->public class Handler : IHttpHandler
{
    private bool ok = true; 

    public void ProcessRequest(HttpContext context)
    {
        ok = true;
        while (ok)//超时设置ok为false即可
        {
            //循环检查是否有信息存在
            Check(); 

            //防止循环太频繁 
            System.Threading.Thread.Sleep(1000);
        }
    } 

    private void Check()
    {
        List<message> list = new List<message>();//信息列表 

        string str = "";
        lock (im.mlist)
        {
            if (im.mlist.Count > 0)
            {
                foreach (message m in im.mlist)
                {
                    if (m.username == HttpContext.Current.Request["name"].ToString())
                    {
                        list.Add(m);
                        str = m.messagecontent;
                        break;
                    }
                } 

                if (list.Count > 0)
                {
                    foreach (message m in list)
                    {
                        im.mlist.Remove(m);
                    }
                } 

                //收到信息 循环结束
                ok = false; 

                if (list.Count > 0)
                {
                    //推信息
                    HttpContext.Current.Response.Write("收到信息:" + str);
                }
            }
        }
    } 

    public bool IsReusable
    {
        get
        {
            return false;
        }
    } 

}
posted @ 2015-03-22 12:09  DBNull  阅读(273)  评论(0编辑  收藏  举报