一、eventsource前台代码
①JS代码
if(typeof EventSource != "undefined")
{
var source = new EventSource("MyCommon.ashx");
//e.data在onopen事件里是undefined
source.onopen = function (e) {
document.getElementById("result").innerHTML += "<br/>" + "已连接" + "<br/>";
};
source.onmessage = function (e) {
document.getElementById("result").innerHTML += "onmessage" + e.data + "<br/>" + e.target.url + "<br/>" + e.target.readyState + "<br/>";
};
//e.data在onerror事件里是undefined
source.onerror = function (e) {
document.getElementById("result").innerHTML += "连接失败" + "<br/>";
};
}
else
{
document.getElementById("result").innerHTML = "不支持您老的浏览器~"
}
②HTML控件
<div id="result"></div>
二、ASHX代码
public void ProcessRequest(HttpContext context)
{
//设置类型
context.Response.ContentType = "text/event-stream";
//Provisional headers are shown
//Accept:text/event-stream
//Cache-Control:no-cache
//context.Response.Headers.Set("Cache-Control", "no-cache"); //这种不行
//禁止页面缓存的可行2种形式
context.Response.Cache.SetNoStore();//Cache-Control:private, no-store//可以
// TimeSpan TS = new TimeSpan(0);
// context.Response.Cache.SetMaxAge(TS);//Cache-Control:private, max-age=0//可以
string time = "data:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\n\n";//数据前面必须以data:开头,后面必须有两个换行
context.Response.Write(time);
}