当客户端需要定时轮询服务器获取一些消息的时候,可以使用 servser-sent events
.NET 服务端:
1 public void ProcessRequest(HttpContext context) 2 { 3 context.Response.ContentType = "text/event-stream"; 4 context.Response.Write("retry: 1000 ");//告诉客户端请求的时间间隔 5 context.Response.Write("data: " + DateTime.Now.ToString() + " ");//返回的数据格式 data:... 6 context.Response.Flush(); 7 }
客户端:
1 <!DOCTYPE html> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 5 <title></title> 6 <script> 7 function listener(event) { 8 var div = document.getElementById("main"); 9 div.innerHTML += event.data +"<br/>"; 10 } 11 12 var es = new EventSource("/SSE_Server.ashx"); 13 14 es.addEventListener("open", function (e) { 15 var msg = ""; 16 if (e.target.readyState == EventSource.CONNECTING) { 17 msg = "链接中..."; 18 } else if (e.target.readyState == EventSource.OPEN) { 19 msg = "OPEN"; 20 } else if (e.target.readyState == EventSource.CLOSED) { 21 msg = "CLOSED"; 22 } 23 var div = document.getElementById("main"); 24 div.innerHTML += msg + "<br/>"; 25 }); 26 es.addEventListener("message", listener); 27 es.addEventListener("error", function (e) { 28 var msg =""; 29 if(e.target.readyState==EventSource.CONNECTING) 30 { 31 msg = "等待链接"; 32 } else if (e.target.readyState == EventSource.CLOSED) 33 { 34 msg = "链接失败"; 35 } 36 var div = document.getElementById("main"); 37 div.innerHTML += msg + "<br/>"; 38 }); 39 </script> 40 </head> 41 <body> 42 <div id="main"> 43 </div> 44 </body> 45 </html>
效果展示:
附:
服务器可返回下列字段格式:
1 Fields
2 3 The following field names are defined by the specification: 4 5 event 6 The event's type. If this is specified, an event will be dispatched on the browser to the listener for the specified event name;
the web site source code should use addEventListener() to listen for named events. The onmessage handler is called if no event name is specified for a message. 7 data 8 The data field for the message. When the EventSource receives multiple consecutive lines that begin with data:, it will concatenate them, inserting a newline character between each one.
Trailing newlines are removed. 9 id 10 The event ID to set the EventSource object's last event ID value. 11 retry 12 The reconnection time to use when attempting to send the event. [What code handles this?] This must be an integer, specifying the reconnection time in milliseconds.
If a non-integer value is specified the field is ignored.