SSE: server-sent events

时间:2022-12-19 19:21:02

  当客户端需要定时轮询服务器获取一些消息的时候,可以使用 servser-sent events

  .NET 服务端:  

         public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/event-stream";
context.Response.Write("retry: 1000\n");//告诉客户端请求的时间间隔
context.Response.Write("data: " + DateTime.Now.ToString() + " \n\n");//返回的数据格式 data:...
context.Response.Flush();
}

  客户端:  

 <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script>
function listener(event) {
var div = document.getElementById("main");
div.innerHTML += event.data +"<br/>";
} var es = new EventSource("/SSE_Server.ashx"); es.addEventListener("open", function (e) {
var msg = "";
if (e.target.readyState == EventSource.CONNECTING) {
msg = "链接中...";
} else if (e.target.readyState == EventSource.OPEN) {
msg = "OPEN";
} else if (e.target.readyState == EventSource.CLOSED) {
msg = "CLOSED";
}
var div = document.getElementById("main");
div.innerHTML += msg + "<br/>";
});
es.addEventListener("message", listener);
es.addEventListener("error", function (e) {
var msg ="";
if(e.target.readyState==EventSource.CONNECTING)
{
msg = "等待链接";
} else if (e.target.readyState == EventSource.CLOSED)
{
msg = "链接失败";
}
var div = document.getElementById("main");
div.innerHTML += msg + "<br/>";
});
</script>
</head>
<body>
<div id="main">
</div>
</body>
</html>

  效果展示:

  SSE: server-sent events

附:

服务器可返回下列字段格式:

 Fields

The following field names are defined by the specification: event
  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.
data
  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.
id
  The event ID to set the EventSource object's last event ID value.
retry
  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.