[ASP.NET MVC] Real-time之HTML5 服务器发送事件(server-sent event)
2016-04-18 11:55
881 查看
最近有时间,打算看看SignalR,顺便了解一下Server Sent Events。
Controller
输出的数据格式为:data:[数据]\n\n。输出的数据尝试8000多字符也没问题,具体的上限就没试了。但是如果数据里也包含\n\n的话,数据就会被截断。
View
运行如下:
Controller
输出的数据格式为:data:[数据]\n\n。输出的数据尝试8000多字符也没问题,具体的上限就没试了。但是如果数据里也包含\n\n的话,数据就会被截断。
public class HomeController : Controller { // GET: Home public ActionResult Index() { return View(); } //Server-Sent Event public void Sse() { Random random = new Random(); //设置HTTP MIME 类型,不缓存页面 Response.ContentType = "text/event-stream"; Response.CacheControl = "no-cache"; while (Response.IsClientConnected) { try { string data = SseData(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " from http://www.cnblogs.com/ainijiutian/"); Response.Write(data); Response.Flush(); System.Threading.Thread.Sleep(random.Next(500, 5000)); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } }; Response.End(); Response.Close(); } //SSE data private string SseData(string data) { return "data:" + data + "\n\n"; } }
View
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <div id="container"> </div> <script> if (typeof (EventSource) !== "undefined") { var container = document.getElementById("container"); var es = new EventSource("/home/sse"); es.onopen = function (event) { container.innerHTML += "open<br/>"; } es.onmessage = function (event) { container.innerHTML += event.data + "<br/>"; }; es.onerror = function (event) { container.innerHTML += "error<br/>"; es.close(); } } else { console.log("一边儿玩儿去"); } </script> </body> </html>
运行如下:
相关文章推荐
- 【Bugly干货分享】一起用 HTML5 Canvas 做一个简单又骚气的粒子引擎
- H5页面快速搭建之高级字体应用实践
- H5页面快速搭建之高级字体应用实践
- H5页面快速搭建之高级字体应用实践
- 利用HTML5定位功能获取经纬度,在根据经纬度利用百度地图获取位置信息
- HTML5 之 图片墙
- 利用HTML5分片上传超大文件
- 开源ckplayer 网页播放器, 跨平台(html5, mobile),flv, f4v, mp4, rtmp协议. webm, ogg, m3u8 !
- html5 localStorage and sessionStorage
- CDH5.7快速离线安装教程
- html5新内容
- HTML5 实现橡皮擦的擦除效果
- HTML5 Canvas图片马赛克模糊动画
- HTML5新功能总结
- IE6/7/8兼容HTML5和css3
- 百度H5开始公测
- 二,细说 HTML5 之 HTML5 基础讲解 2
- h5城市定位
- 一,细说 HTML5 之 HTML5 基础讲解
- Html5,CSS3实现一个七夕贺卡(仿)