简单搭建http服务器-HttpListener使用

红太狼 2023-10-10 09:21 79阅读 0赞

使用HTTPListener可以简单搭建一个Http服务器,对于本地使用很是方面,想起之前使用了WebSocket来与本地网页通讯的例子,也是可以改为使用HTTPListener来做的。看下HTTPListener的使用吧。

  1. public class RJHttp
  2. {
  3. private HttpListener httpListener = new HttpListener();
  4. public RJHttp()
  5. {
  6. this.httpListener.Prefixes.Add("http://127.0.0.1:8089/");//必须以/结尾
  7. this.httpListener.Start();
  8. ///异步等待请求
  9. this.httpListener.BeginGetContext(this.Read, this.httpListener);
  10. }
  11. private void Read(IAsyncResult result)
  12. {
  13. ///获取到请求
  14. HttpListenerContext context = this.httpListener.EndGetContext(result);
  15. ///获取请求的数据
  16. HttpListenerRequest request = context.Request;
  17. string contentType = request.ContentType;
  18. string httpMethod = request.HttpMethod;
  19. string userAgent = request.UserAgent;
  20. StreamReader sr = new StreamReader(request.InputStream);
  21. string code = sr.ReadToEnd();
  22. ///返回数据
  23. byte[] bys = Encoding.UTF8.GetBytes(DateTime.Now.ToString());
  24. context.Response.OutputStream.Write(bys, 0, bys.Length);
  25. context.Response.Close();
  26. this.httpListener.BeginGetContext(this.Read, this.httpListener);
  27. }
  28. }

对于请求端使用的什么请求方式可以使用request.HttpMethod的值进行判断,然后返回指定的数据即可。

转载于:https://www.cnblogs.com/zzr-stdio/p/11393241.html

发表评论

表情:
评论列表 (有 0 条评论,79人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Http服务器

    一、Nginx介绍 > Nginx是一个高性能的HTTP和方向代理服务,也是一个IMAP/POP3/SMTP服务。 > > 其特点是占用内存少,并发能力强,中国大陆使用