Frage

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.

War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top