【通过HttpListener实现简单的Http服务】

绝地灬酷狼 2022-08-21 05:56 259阅读 0赞

使用HttpListener实现简单的Http服务。

HttpListener 提供一个简单的、可通过编程方式控制的 HTTP 协议侦听器.使用它可以很容易的提供一些Http服务,而无需启动IIS这类大型服务程序。

使用HttpListener的方法流程很简单:主要分为以下几步

  1. 创建一个HTTP侦听器对象并初始化
  2. 添加需要监听的URI 前缀
  3. 开始侦听来自客户端的请求
  4. 处理客户端的Http请求
  5. 关闭HTTP侦听器

例如:我们要实现一个简单Http服务,进行文件的下载,或者进行一些其他的操作,例如要发送邮件,使用HttpListener监听,处理邮件队列,避免在网站上的同步等待。以及获取一些缓存的数据等等行为。

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Web;
  8. using System.IO;
  9. using Newtonsoft.Json;
  10. namespace HttpListenerApp
  11. {
  12. /// <summary>
  13. /// HttpRequest逻辑处理
  14. /// </summary>
  15. public class HttpProvider
  16. {
  17. private static HttpListener httpFiledownload; //文件下载处理请求监听
  18. private static HttpListener httOtherRequest; //其他超做请求监听
  19. /// <summary>
  20. /// 开启HttpListener监听
  21. /// </summary>
  22. public static void Init()
  23. {
  24. httpFiledownload = new HttpListener(); //创建监听实例
  25. httpFiledownload.Prefixes.Add("http://10.0.0.217:20009/FileManageApi/Download/"); //添加监听地址 注意是以/结尾。
  26. httpFiledownload.Start(); //允许该监听地址接受请求的传入。
  27. Thread ThreadhttpFiledownload = new Thread(new ThreadStart(GethttpFiledownload)); //创建开启一个线程监听该地址得请求
  28. ThreadhttpFiledownload.Start();
  29. httOtherRequest = new HttpListener();
  30. httOtherRequest.Prefixes.Add("http://10.0.0.217:20009/BehaviorApi/EmailSend/"); //添加监听地址 注意是以/结尾。
  31. httOtherRequest.Start(); //允许该监听地址接受请求的传入。
  32. Thread ThreadhttOtherRequest = new Thread(new ThreadStart(GethttOtherRequest));
  33. ThreadhttOtherRequest.Start();
  34. }
  35. /// <summary>
  36. /// 执行文件下载处理请求监听行为
  37. /// </summary>
  38. public static void GethttpFiledownload()
  39. {
  40. while (true)
  41. {
  42. HttpListenerContext requestContext = httpFiledownload.GetContext(); //接受到新的请求
  43. try
  44. {
  45. //reecontext 为开启线程传入的 requestContext请求对象
  46. Thread subthread = new Thread(new ParameterizedThreadStart((reecontext) =>
  47. {
  48. Console.WriteLine("执行文件处理请求监听行为");
  49. var request = (HttpListenerContext)reecontext;
  50. var image = HttpUtility.UrlDecode(request.Request.QueryString["imgname"]); //接受GET请求过来的参数;
  51. string filepath = AppDomain.CurrentDomain.BaseDirectory + image;
  52. if (!File.Exists(filepath))
  53. {
  54. filepath = AppDomain.CurrentDomain.BaseDirectory + "default.jpg"; //下载默认图片
  55. }
  56. using (FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read))
  57. {
  58. byte[] buffer = new byte[fs.Length];
  59. fs.Read(buffer, 0, (int)fs.Length); //将文件读到缓存区
  60. request.Response.StatusCode = 200;
  61. request.Response.Headers.Add("Access-Control-Allow-Origin", "*");
  62. request.Response.ContentType = "image/jpg";
  63. request.Response.ContentLength64 = buffer.Length;
  64. var output = request.Response.OutputStream; //获取请求流
  65. output.Write(buffer, 0, buffer.Length); //将缓存区的字节数写入当前请求流返回
  66. output.Close();
  67. }
  68. }));
  69. subthread.Start(requestContext); //开启处理线程处理下载文件
  70. }
  71. catch (Exception ex)
  72. {
  73. try
  74. {
  75. requestContext.Response.StatusCode = 500;
  76. requestContext.Response.ContentType = "application/text";
  77. requestContext.Response.ContentEncoding = Encoding.UTF8;
  78. byte[] buffer = System.Text.Encoding.UTF8.GetBytes("System Error");
  79. //对客户端输出相应信息.
  80. requestContext.Response.ContentLength64 = buffer.Length;
  81. System.IO.Stream output = requestContext.Response.OutputStream;
  82. output.Write(buffer, 0, buffer.Length);
  83. //关闭输出流,释放相应资源
  84. output.Close();
  85. }
  86. catch { }
  87. }
  88. }
  89. }
  90. /// <summary>
  91. /// 执行其他超做请求监听行为
  92. /// </summary>
  93. public static void GethttOtherRequest()
  94. {
  95. while (true)
  96. {
  97. HttpListenerContext requestContext = httOtherRequest.GetContext(); //接受到新的请求
  98. try
  99. {
  100. //reecontext 为开启线程传入的 requestContext请求对象
  101. Thread subthread = new Thread(new ParameterizedThreadStart((reecontext) =>
  102. {
  103. Console.WriteLine("执行其他超做请求监听行为");
  104. var request = (HttpListenerContext)reecontext;
  105. var msg = HttpUtility.UrlDecode(request.Request.QueryString["behavior"]); //接受GET请求过来的参数;
  106. //在此处执行你需要进行的操作>>比如什么缓存数据读取,队列消息处理,邮件消息队列添加等等。
  107. request.Response.StatusCode = 200;
  108. request.Response.Headers.Add("Access-Control-Allow-Origin", "*");
  109. request.Response.ContentType = "application/json";
  110. requestContext.Response.ContentEncoding = Encoding.UTF8;
  111. byte[] buffer = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new { success = true, behavior = msg }));
  112. request.Response.ContentLength64 = buffer.Length;
  113. var output = request.Response.OutputStream;
  114. output.Write(buffer, 0, buffer.Length);
  115. output.Close();
  116. }));
  117. subthread.Start(requestContext); //开启处理线程处理下载文件
  118. }
  119. catch (Exception ex)
  120. {
  121. try
  122. {
  123. requestContext.Response.StatusCode = 500;
  124. requestContext.Response.ContentType = "application/text";
  125. requestContext.Response.ContentEncoding = Encoding.UTF8;
  126. byte[] buffer = System.Text.Encoding.UTF8.GetBytes("System Error");
  127. //对客户端输出相应信息.
  128. requestContext.Response.ContentLength64 = buffer.Length;
  129. System.IO.Stream output = requestContext.Response.OutputStream;
  130. output.Write(buffer, 0, buffer.Length);
  131. //关闭输出流,释放相应资源
  132. output.Close();
  133. }
  134. catch { }
  135. }
  136. }
  137. }
  138. }
  139. }

调用方式:注意这里启动程序必须以管理员身份运行,因为上午的监听需要开启端口,所有需要以管理员身份运行。

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace HttpListenerApp
  6. {
  7. class Program
  8. {
  9. static void Main(string[] args)
  10. {
  11. //开启请求监听
  12. HttpProvider.Init();
  13. }
  14. }
  15. }

执行后的结果为:

20160420154103435

这里通过一个简单的控制程序在里面使用HttpListener实现了简单的Http服务程序。里面有少量的线程和和异步处理,比如收到行为信息请求可以先返回给用户,让用户不用同步等待,就可以执行下一步操作,又比如实现的简单邮件服务器,将请求发给HttpListener接收到请求后就立即返回,交给队列去发送邮件。邮件的发送会出现延迟等待等情况出现,这样就不用等待。等等

发表评论

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

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

相关阅读