使用长轮询替代:
js:
//===============SendEvent================
//控制是否继续轮询
var isEventClose = 1;
//创建XMLHttpRequest
function createXmlHttpRequest() {
if (window.ActiveXObject) { //如果是IE浏览器
return new ActiveXObject("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest) { //非IE浏览器
return new XMLHttpRequest();
}
}
//初始化
var xhr = createXmlHttpRequest();
//方法入口
function EdgeEvent() {
xhr.open("post", "/eventEdge.webapi",true);
xhr.onreadystatechange = AppendMessage;
xhr.send();
}
//增加消息
function AppendMessage() {
if (xhr.readyState == 4 && xhr.status == 200) {
if (xhr.responseText != null && xhr.responseText.length > 0) {
$("#publishMessage").append(xhr.responseText);
}
if (isEventClose == 0) {
setTimeout(EdgeEvent, 500);
}
}
};
//===============SendEvent================
后台:
public static void SendEdgeEvent(HttpListenerResponse response)
{
var output = response.OutputStream;
response.Headers.Add("Cache-Control", "no-cache");
response.ContentType = "text/xml;charset=UTF-8";
while (_messageQuery.Count > 0)
{
var message = _messageQuery.Dequeue();
var data = Encoding.UTF8.GetBytes($"{ message }\n");
output.Write(data, 0, data.Length);
output.Flush();
}
}