[英]How to detect a disconnection when using Server-sent events on ASP.NET?
I have the following SSE handler in ASP.NET 我在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);
}
It runs indefinitely, even after I closed the client application. 即使我关闭了客户端应用程序,它也可以无限期运行。 How to notify the server to stop the handler?
如何通知服务器停止处理程序?
I tried on the client: 我在客户端上尝试过:
var source = new EventSource('Handler.aspx');
window.onunload = function() {
source.close();
}
But I didn't succeed. 但是我没有成功。
You could use the IsClientConnected
property of the HttpResponse
class to detect client diconnection. 您可以使用
HttpResponse
类的IsClientConnected
属性来检测客户端断开连接。
Here is a small example: 这是一个小例子:
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);
}
So, using the IsClientConnected
property you should be able to detect: 因此,使用
IsClientConnected
属性,您应该能够检测到:
source.close()
. source.close()
关闭源。 I've tested my code using ASP.Net 4.0 and Google Chrome. 我已经使用ASP.Net 4.0和Google Chrome测试了我的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.