How to detect a disconnection as soon as it happens on ASP.NET without polling?

不想你离开。 提交于 2019-12-12 06:05:54

问题


I have a server-sent events handler in ASP.NET

Response.ContentType = "text/event-stream";
while (true)
{
   if(thereIsAMessage)
   {
       Response.Write(message);
       Response.Flush();
       if (Response.IsClientConnected == false)
       {
           break;
       }
   }

   System.Threading.Thread.Sleep(1000);
}

The problem is that I can only detect a client disconnection when I send something to the client. And I don't want to poll it, which defeats the whole purpose of using Server-sent events in the first place.


回答1:


Try to look at SignalR - useful for long polling, server notifications won't be difficult to implement. Uses websockets when available. Yours scenario can be implemented very easily using hubs.




回答2:


If you want to do in your own code, you can simply modify your example:

Response.ContentType = "text/event-stream";
while (Response.IsClientConnected)
{
   if(thereIsAMessage)
   {
       Response.Write(message);
       Response.Flush();
   }

   System.Threading.Thread.Sleep(1000);
}

But still, I'm not sure this is optimal implementation using Thread.Sleep approach.



来源:https://stackoverflow.com/questions/9771581/how-to-detect-a-disconnection-as-soon-as-it-happens-on-asp-net-without-polling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!