Question

I have the following SSE handler in ASP.NET

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.

Was it helpful?

Solution

You could use the IsClientConnected property of the HttpResponse class to detect client diconnection.

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:

  1. On the client side closing the source by using 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top