Ajax 长连接
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请求
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; } } }
相关推荐
kentrl 2020-11-10
结束数据方法的参数,该如何定义?-- 集合为自定义实体类中的结合属性,有几个实体类,改变下标就行了。<input id="add" type="button" value="新增visitor&quo
ajaxyan 2020-11-09
zndy0 2020-11-03
学留痕 2020-09-20
Richardxx 2020-11-09
learningever 2020-09-19
chongxiaocheng 2020-08-16
ajaxhe 2020-08-16
lyqdanang 2020-08-16
curiousL 2020-08-03
TONIYH 2020-07-22
时光如瑾雨微凉 2020-07-19
83510998 2020-07-18
坚持着执着 2020-07-16
jiaguoquan00 2020-07-07
李永毅 2020-07-05
坚持着执着 2020-07-05