Search code examples
c#asp.nethttpkeep-alivegeneric-handler

Keeping a HttpHandler alive / flushing intermediate data


Background: we are having issues with one of our GPRS devices connecting through a proxy to a generic handler. Although the handler closes the connection immediately after returning, the proxy keeps the connection open, which the device does not expect.

My question: is it possible, for testing purposes (in order to mimic the proxy's behavior), to keep the connection alive for some short time, after a handler has returned its data?

For example, this does not work:

public class Ping : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.BufferOutput = false;

        context.Response.ContentType = "text/plain";
        context.Response.WriteLine("HELLO");
        context.Response.Flush();  // <-- this doesn't send the data

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

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

[Edit]

Ok, actually, it works as expected. The problem is that both Firefox and Fiddler delay showing the raw data until the connection is closed.

If Response.BufferOutput is set to false, and I use a terminal program to connect, I get the data immediately, and the connection remains open for 10s.


Solution

  • You can write to the output stream and this will do what you want.

    byte [] buffer = new byte[1<<16] // 64kb
    int bytesRead = 0;
    using(var file = File.Open(path))
    {
       while((bytesRead = file.Read(buffer, 0, buffer.Length)) != 0)
       {
            Response.OutputStream.Write(buffer, 0, bytesRead);
             // can sleep here or whatever
       }
    }
    Response.Flush();
    Response.Close();
    Response.End();
    

    Check out Best way to stream files in ASP.NET