[ASP.NET MVC] Real-time之HTML5 服务器发送事件(server-sent event)

时间:2024-07-09 11:05:20

最近有时间,打算看看SignalR,顺便了解一下Server Sent Events。

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(, ));
}
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>

运行如下:

[ASP.NET MVC] Real-time之HTML5 服务器发送事件(server-sent event)