Javascript 事件源;服务器发送事件
我正在尝试处理从浏览器发送到我的C#Web服务器的源代码 当我得到HTTP请求时(get/event/api/endpoint)。。我的答复是: -200好的 -内容类型:文本/事件流 -正文:数据:null 控制台成功地记录了信息。在服务器上,我保持连接打开,响应流也打开。我的服务器似乎没有通过已打开的TCP Response.Outputstream发送后续事件 浏览器(Chrome)发送新事件的问题在于,连接已关闭,但未关闭 客户端代码:Javascript 事件源;服务器发送事件,javascript,c#,httplistener,eventsource,Javascript,C#,Httplistener,Eventsource,我正在尝试处理从浏览器发送到我的C#Web服务器的源代码 当我得到HTTP请求时(get/event/api/endpoint)。。我的答复是: -200好的 -内容类型:文本/事件流 -正文:数据:null 控制台成功地记录了信息。在服务器上,我保持连接打开,响应流也打开。我的服务器似乎没有通过已打开的TCP Response.Outputstream发送后续事件 浏览器(Chrome)发送新事件的问题在于,连接已关闭,但未关闭 客户端代码: <html lang="en"> &l
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
<title>SSE Test</title>
</head>
<body style="background: #fff;">
<div id="infoPane">
</div>
</body>
<script>
(function() {
var infoPane = document.getElementById('infoPane');
var report = function(msg) {
var info = document.createElement('p');
info.textContent = msg;
infoPane.appendChild(info);
};
var source = 'http://localhost:8011/SSE/now';
var loader = new EventSource(source);
loader.onmessage = function (event) {
report(event.data);
};
}());
</script>
</html>
var listener = new HttpListener();
listener.Prefixes.Add("http://+:8011/SSE/");
listener.Start();
Task.Run(() =>
{
while (true)
{
var ctx = listener.GetContext();
Task.Run(() =>
{
var response = ctx.Response;
response.StatusCode = (int)HttpStatusCode.OK;
response.ContentType = "text/event-stream";
response.ContentEncoding = Encoding.UTF8;
try
{
while (true)
{
var msg = string.Format("data: it is now {0} Zulu\n\n", DateTime.UtcNow);
var bytes = Encoding.UTF8.GetBytes(msg);
response.OutputStream.Write(bytes, 0, bytes.Length);
response.OutputStream.Flush();
System.Threading.Thread.Sleep(1000);
}
}
catch (HttpListenerException)
{
}
});
}
});
也修复了它
这是MSFT HttpListener的限制。。我必须在TCPClient之上从头开始构建自己的C#HTTP和HTTPS Web服务器。。这肯定比MSFT实现好上百倍