views:

258

answers:

1

Hi,

msdn give's us this example to retrieve the post data.

 public static void ShowRequestData (HttpListenerRequest request)
 {
     if (!request.HasEntityBody)
     {
         Console.WriteLine("No client data was sent with the request.");
         return;
     }
     System.IO.Stream body = request.InputStream;
     System.Text.Encoding encoding = request.ContentEncoding;
     System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
     if (request.ContentType != null)
     {
         Console.WriteLine("Client data content type {0}", request.ContentType);
     }
     Console.WriteLine("Client data content length {0}", request.ContentLength64);

     Console.WriteLine("Start of client data:");
     // Convert the data to a string and display it on the console.
     string s = reader.ReadToEnd();
     Console.WriteLine(s);
     Console.WriteLine("End of client data:");
     body.Close();
     reader.Close();
     // If you are finished with the request, it should be closed also.
 }

source

I checked the Streamreader class and there are no Begin... End... methods. Does this mean the Post data can not be retrieved asynchronously? Or has it already been retrieved before the callback from the HttpListener came?

I would not like to get a thread-stall while a chunk of slow post data comes in.

What is the correct asynchronous way to do this? (or is the ReadToEnd in fact correct?)

thanks

R

A: 

Instead of using StreamReader you could call Stream.BeginRead on your incoming stream.


UPDATE: Here's an example of using BeginRead on a stream:

class State
{
    public Stream Stream { get; set; }
    public byte[] Buffer { get; set; }
}

class Program
{
    private const int ChunkSize = 1024;
    static void Main(string[] args)
    {
        var stream = new FileStream("test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        var state = new State { Stream = stream, Buffer = new byte[ChunkSize] };
        var ar = stream.BeginRead(state.Buffer, 0, state.Buffer.Length, Callback, state);
        while (!ar.IsCompleted)
        {
            Thread.Sleep(10);
        }
    }

    static void Callback(IAsyncResult ar)
    {
        var state = (State)ar.AsyncState;
        var bytesRead = state.Stream.EndRead(ar);
        if (bytesRead > 0)
        {
            byte[] buffer = new byte[bytesRead];
            Buffer.BlockCopy(state.Buffer, 0, buffer, 0, bytesRead);
            // Do something with the received buffer.
            Console.Write(Encoding.UTF8.GetString(buffer));

            state.Stream.BeginRead(state.Buffer, 0, state.Buffer.Length, Callback, state);
        }
        else
        {
            // reached the end of the stream
            state.Stream.Dispose();
        }
    }
}
Darin Dimitrov
great! thanks...!
Toad