简单的异步HTTP服务端和客户端
Posted 智信智爱智强不息
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简单的异步HTTP服务端和客户端相关的知识,希望对你有一定的参考价值。
/// <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服务端和客户端的主要内容,如果未能解决你的问题,请参考以下文章
Netty入门——springboot框架开发一个简单的服务器端和客户端