使用長輪詢替代:javascript
js:java
//===============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================
後臺:web
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(); } }