首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从HttpListenerRequest异步获取post数据可能吗?

从HttpListenerRequest异步获取post数据可能吗?
EN

Stack Overflow用户
提问于 2009-10-17 14:25:23
回答 1查看 1.6K关注 0票数 0

msdn给我们这个例子来检索post数据。

代码语言:javascript
复制
 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

我检查了Streamreader类,没有开始...结束..。方法。这是否意味着无法异步检索Post数据?或者在HttpListener的回调到来之前,它已经被检索到了?

我不想在一个慢速post数据块进来的时候得到线程停顿。

执行此操作的正确异步方式是什么?(或者ReadToEnd实际上是正确的?)

谢谢

R

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2009-10-17 14:30:25

您可以在传入的流上调用Stream.BeginRead,而不是使用StreamReader

更新:下面是一个在流上使用BeginRead的示例:

代码语言:javascript
复制
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();
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1582309

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档