SSE:服务器发送事件,使用长链接进行通讯 基础学习
HTML5中新加了EventSounce对象,实现即时推送功能,可以从下面连接中学习,
http://www.kwstu.com/ArticleView/kwstu_201408290647460932
http://www.cnblogs.com/goody9807/p/4257192.html
http://www.cnblogs.com/winhu/p/3435262.html?utm_source=tuicool&utm_medium=referral
但最后发现,这种号称由服务器主动推送也不完全准确,比如:
var es = new EventSource("/Home/GetDate"); es.onopen = function (e) { document.getElementById("state").innerHTML=("正在连接....") } es.onmessage = function (e) { document.getElementById("state").innerHTML=("已连接") $("#msg").append(e.data); }; es.addEventListener('myevent', function (e) { document.getElementById("state").innerHTML=("出错???? "); console.log(e.data); }); $(function () { $("#btn").click(function () { $.post("/Home/Set", null, function (date) { alert(date); }); }); }) </script></head> <body> <button id="btn">改变值</button> <div> 状态:<div id="state"></div> 消息:<div id="msg"></div> </div> </body>
public string value { get; set; }
public void GetDate() { try { var data = GetData(); HttpContext.Response.ContentType = "text/event-stream"; HttpContext.Response.CacheControl = "no-cache"; HttpContext.Response.Write("data:" + data + "\n\n"); HttpContext.Response.Flush(); Thread.Sleep(1000); } catch (Exception) { } } private object GetData() { return this.value; } public ActionResult Set() { Random r = new Random(); this.value = r.Next(30)+""; return Content("ok"); }
上面实际运行时,每隔几秒客户端浏览器就会向服务器发出连接,就会把服务器value值返回到网页上,其实value值没有发生变化,一般不变的情况我们是不需要在网页中显示的,也就是不做处理,但每次隔几秒就连接服务器会不会消耗资源,带来浪费,这种好像也不是服务器主动推送数据吧,如果对GetDate函数做一改动,如下,增加while循环就成了长轮训了,长时间与客户端保持连接,但从客户端改变value值总是不成功,可能是能力不够,但到现在我也没想出好办法,HTML5的EventSource到底是如何使用还需要时间研究.....
public void GetDate() { try { HttpContext.Response.ContentType = "text/event-stream"; HttpContext.Response.CacheControl = "no-cache"; while (true) { var data = GetData(); HttpContext.Response.Write("data:" + data + "\n\n"); HttpContext.Response.Flush(); Thread.Sleep(1000); } } catch (Exception) { } }