Search code examples
c#asp.netreal-timeresponsegeneric-handler

How to create a method to send some real-time data using generic handler?


I have a page waiting for response of a Generic Handler with this javascript code:

if (typeof (EventSource) !== "undefined") {
var source = new EventSource("../Handler/EventHandler.ashx");
source.onmessage = function (event) {
    alert(event.data);
   };
} 

and this handler:

public void ProcessRequest(HttpContext context)
{
        context.Response.ContentType = "text/event-stream";
        context.Response.Write("data: Event handler started");
        context.Response.Flush();
        context.Response.Close();
}

Now I want to have a method (in handler) ,like this to send some real-time data through ashx to my page:

public void send(string data){
    //send through ashx
}

How can I write this method to be callable from other classes? Can I use thread?


Solution

  • Your ProcessRequest server side method should never end:

    public void ProcessRequest(HttpContext context)
    {
        Response.ContentType = "text/event-stream";
    
        var source = new SomeEventSource();
        source.OnSomeEvent += data =>
        {
            context.Response.Write(data);
            context.Response.Flush();
        }
    
        while (true)
        {
            System.Threading.Thread.Sleep(1000);
        }
    
        Response.Close();
    }
    

    This being said, using a forever blocking loop in the ProcessRequest method would be terrible in terms of resource consumption. You should absolutely consider using an IHttpAsyncHander instead of an IHttpHandler. This would allow you to free the worker thread while waiting for notifications from the external source.