0

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.

vgru
  • 49,838
  • 16
  • 120
  • 201

2 Answers2

1

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

Community
  • 1
  • 1
Dave Walker
  • 3,498
  • 1
  • 24
  • 25
  • Thanks. It turned out that I didn't actually need to do it this way, but your suggestion worked nevertheless. It seems that a simple flush works as expected after all. – vgru Dec 07 '11 at 11:53
0

Actually, this works fine after all:

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

        context.Response.ContentType = "text/plain";
        context.Response.WriteLine("HELLO"); // <-- data is sent immediately

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

I had to use a terminal program to connect, but then it turned out to be ok.

One thing that should be mentioned is that ASP adds a Transfer-Encoding: chunked header in this case, which changes the way data is sent:

The size of each chunk is sent right before the chunk itself so that a client can tell when it has finished receiving data for that chunk. The data transfer is terminated by a final chunk of length zero.

vgru
  • 49,838
  • 16
  • 120
  • 201