我在 ASP.NET 中有以下 SSE 处理程序
Response.ContentType = "text/event-stream";
while (true)
{
Response.Write(string.Format("data: {0}\n\n", DateTime.Now.ToString()));
Response.Flush();
System.Threading.Thread.Sleep(1000);
}
它会无限期地运行,即使在我关闭客户端应用程序之后也是如此。如何通知服务器停止处理程序?
我在客户端试过:
var source = new EventSource('Handler.aspx');
window.onunload = function() {
source.close();
}
但是我没有成功。
最佳答案
您可以使用 HttpResponse
类的 IsClientConnected
属性来检测客户端断开连接。
这是一个小例子:
Response.ContentType = "text/event-stream";
while (true)
{
Response.Write(string.Format("data: {0}\n\n", DateTime.Now.ToString()));
Response.Flush();
if (Response.IsClientConnected == false)
{
break;
}
System.Threading.Thread.Sleep(1000);
}
因此,使用 IsClientConnected
属性您应该能够检测到:
- 在客户端使用
source.close()
关闭源。 - 通过关闭浏览器窗口或导航到另一个网站来关闭连接。
我已经使用 ASP.Net 4.0 和 Google Chrome 测试了我的代码。
关于c# - 在 ASP.NET 上使用服务器发送的事件时如何检测断开连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9743253/