码迷,mamicode.com
首页 > Web开发 > 详细

简单的异步HTTP服务端和客户端

时间:2016-03-10 14:08:41      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:

 /// <summary>
        /// 异步Http服务器
        /// </summary>
        class AsyncHttpServer
        {
            readonly HttpListener _listener;
            //相应信息
            const string RESPONSE_TEMPLATE = "<html><head><title>Test</title></head><body><h2>Test page</h2><h4>Today is: {0}</h4></body></html>";

            public AsyncHttpServer(int portNumber)
            {
                _listener = new HttpListener();
                _listener.Prefixes.Add(string.Format("http://+:{0}/", portNumber));
            }

            public async Task Start()
            {
                _listener.Start();

                while (true)
                {
                    var ctx = await _listener.GetContextAsync();
                    Console.WriteLine("Client connected...");
                    var response = string.Format(RESPONSE_TEMPLATE, DateTime.Now);

                    using (var sw = new StreamWriter(ctx.Response.OutputStream))
                    {
                        await sw.WriteAsync(response);
                        await sw.FlushAsync();
                    }
                }
            }

            public async Task Stop()
            {
                _listener.Abort();
            }
        }

  

       /// <summary>
        /// 客户端获取响应信息
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        static async Task GetResponseAsync(string url)
        {
            using (var client = new HttpClient())
            {
                HttpResponseMessage responseMessage = await client.GetAsync(url);
                string responseHeaders = responseMessage.Headers.ToString();
                string response = await responseMessage.Content.ReadAsStringAsync();

                Console.WriteLine("Response headers:");
                Console.WriteLine(responseHeaders);
                Console.WriteLine("Response body:");
                Console.WriteLine(response);
            }
        }

注: 以管理员身份运行程序

简单的异步HTTP服务端和客户端

标签:

原文地址:http://www.cnblogs.com/zhangzhi19861216/p/5261384.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!