简体   繁体   English

在ASP.NET上使用服务器发送的事件时如何检测断开连接?

[英]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属性,您应该能够检测到:

  1. On the client side closing the source by using source.close() . 在客户端,使用source.close()关闭源。
  2. Closing the connection by closing the browser window or navigating to another website. 通过关闭浏览器窗口或导航到另一个网站来关闭连接。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM