在HttpListener中处理发布请求

时间:2012-10-18 10:31:09

标签: c# javascript httplistener

private void ListenerCallback(IAsyncResult ar)
        {
            _busy.WaitOne();
            try
            {
                HttpListenerContext context;
                try
                { context = _listener.EndGetContext(ar); }
                catch (HttpListenerException)
                { return; }

                if (_stop.WaitOne(0, false))
                    return;

                var sr = new StreamReader(context.Request.InputStream);
                string x = sr.ReadToEnd();
                Console.WriteLine("{0} {1}", context.Request.HttpMethod, x);
                //context.Response.SendChunked = true;
                using (TextWriter tw = new StreamWriter(context.Response.OutputStream))
                {
                    //for (int i = 0; i < 5; i++)
                    {
                        //tw.WriteLine("<p>{0} @ {1}</p>", i, DateTime.Now);
                        tw.WriteLine("<html><head></head><body>");
                        tw.WriteLine("Server Response");
                        tw.WriteLine("</body></html>");
                        tw.Flush(); //Catch http exception if client exists halfway through
                        //Thread.Sleep(1000);
                    }
                }
            }
            finally
            {
                if (_maxThreads == 1 + _busy.Release())
                    _idle.Set();
            }
        }

以上是我的代码,即使服务器显示需要2次获取请求,我也可以使用Chrome访问该网址,但很少有回复,我希望能够处理POST请求,当我发送帖子请求时,它会读取它正确,但客户没有得到答复。

1 个答案:

答案 0 :(得分:1)

您应该添加ctx.Response.ContentLength64=...。 (您可能还需要ctx.Response.Close()