EventSource JS实时通信
前台 html
<script type="text/javascript">
if (typeof (EventSource) != "undefined") {
var es = new EventSource("http://localhost:8080/Home/GetNotices?user=lxw");
es.onmessage = function (event) {
//var data = JSON.parse(event.data);
//$('#msgCount').text(data + "</br>")
document.body.innerHTML += event.data + '<br>';
};
es.onopen = function (event) {
console.log("open:" + JSON.stringify(event));
};
es.onerror = function (event) {
console.log("error:" + JSON.stringify(event) + JSON.stringify(es));
};
}
else {
console.log("该浏览器不支持");
}
</script>
后台 asp.net mvc
public void GetNotices(string user)
{
var sb = new System.Text.StringBuilder();
sb.AppendFormat("retry:{0}\n\n", 2000); //推送间隔
sb.AppendFormat("event:{0}\n\n", "message"); //绑定onmessage
sb.AppendFormat("id:{0}\n\n", System.Threading.Thread.CurrentThread.ManagedThreadId);
string info = "当前线程:" + System.Threading.Thread.CurrentThread.ManagedThreadId + " 时间:" + DateTime.Now.ToString()+" 用户:"+ user;
sb.AppendFormat("data:\"{0}\"\n\n", info);
Response.ContentType = "text/event-stream";
Response.Expires = -1;
Response.Write(sb.ToString());
Response.Flush();
}
允许跨域配置
<system.webServer> 节点中添加
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE" />
</customHeaders>
</httpProtocol>