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.
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.
Share Improve this question edited Mar 16, 2012 at 19:19 Dagg Nabbit 76.8k19 gold badges114 silver badges142 bronze badges asked Mar 16, 2012 at 19:17 Jader DiasJader Dias 90.7k160 gold badges435 silver badges633 bronze badges 11- If this is just to show a live clock, you may want to look into a JavaScript equivalent that does the same thing. – AaronS Commented Mar 16, 2012 at 19:22
- 3 @AaronS I'm pretty sure using DateTime.Now is just OPs example. – Bala R Commented Mar 16, 2012 at 19:23
- @Bala R You're probably right, but doesn't hurt to check. – AaronS Commented Mar 16, 2012 at 19:24
-
You'll need to make your
while
breakable and have the client send a message when it wants the server to break. – M.Babcock Commented Mar 16, 2012 at 19:26 - 1 I feel like the best way to do something like this would be a push style request ing from the client, which the server sits on until it's time to respond, responds to, and a new request is immediately opened. Then you never have hanging requests (longer than the timeout, anyway) – Chris Carew Commented Mar 16, 2012 at 19:53
1 Answer
Reset to default 4You 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:
- On the client side closing the source by using
source.close()
. - 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.