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.
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:
source.close()
.I've tested my code using ASP.Net 4.0 and Google Chrome.