欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.NET下通过HttpListener实现简单的Http服务

程序员文章站 2023-12-03 15:09:16
httplistener提供一个简单的、可通过编程方式控制的 http 协议侦听器.使用它可以很容易的提供一些http服务,而无需启动iis这类大型服务程序。使用httpl...

httplistener提供一个简单的、可通过编程方式控制的 http 协议侦听器.使用它可以很容易的提供一些http服务,而无需启动iis这类大型服务程序。使用httplistener的方法流程很简单:主要分为以下几步 

1.创建一个http侦听器对象并初始化 

2.添加需要监听的uri 前缀 

3.开始侦听来自客户端的请求 

4.处理客户端的http请求 

5.关闭http侦听器 

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

using system;
using system.collections.generic;
using system.linq;
using system.net;
using system.text;
using system.threading;
using system.web;
using system.io;
using newtonsoft.json;

namespace httplistenerapp
{
 /// <summary>
 /// httprequest逻辑处理
 /// </summary>
 public class httpprovider
 {

  private static httplistener httpfiledownload; //文件下载处理请求监听
  private static httplistener httotherrequest; //其他超做请求监听

  /// <summary>
  /// 开启httplistener监听
  /// </summary>
  public static void init()
  {
   httpfiledownload = new httplistener(); //创建监听实例
   httpfiledownload.prefixes.add("http://10.0.0.217:20009/filemanageapi/download/"); //添加监听地址 注意是以/结尾。
   httpfiledownload.start(); //允许该监听地址接受请求的传入。
   thread threadhttpfiledownload = new thread(new threadstart(gethttpfiledownload)); //创建开启一个线程监听该地址得请求
   threadhttpfiledownload.start();

   httotherrequest = new httplistener();
   httotherrequest.prefixes.add("http://10.0.0.217:20009/behaviorapi/emailsend/"); //添加监听地址 注意是以/结尾。
   httotherrequest.start(); //允许该监听地址接受请求的传入。
   thread threadhttotherrequest = new thread(new threadstart(gethttotherrequest));
   threadhttotherrequest.start();
  }

  /// <summary>
  /// 执行文件下载处理请求监听行为
  /// </summary>
  public static void gethttpfiledownload()
  {
   while (true)
   {
    httplistenercontext requestcontext = httpfiledownload.getcontext(); //接受到新的请求
    try
    {
     //reecontext 为开启线程传入的 requestcontext请求对象
     thread subthread = new thread(new parameterizedthreadstart((reecontext) =>  
     {
      console.writeline("执行文件处理请求监听行为");

      var request = (httplistenercontext)reecontext;
      var image = httputility.urldecode(request.request.querystring["imgname"]); //接受get请求过来的参数;
      string filepath = appdomain.currentdomain.basedirectory + image;
      if (!file.exists(filepath))
      {
       filepath = appdomain.currentdomain.basedirectory + "default.jpg";  //下载默认图片
      }
      using (filestream fs = new filestream(filepath, filemode.open, fileaccess.read))
      {
       byte[] buffer = new byte[fs.length];
       fs.read(buffer, 0, (int)fs.length); //将文件读到缓存区
       request.response.statuscode = 200;
       request.response.headers.add("access-control-allow-origin", "*");
       request.response.contenttype = "image/jpg"; 
       request.response.contentlength64 = buffer.length;
       var output = request.response.outputstream; //获取请求流
       output.write(buffer, 0, buffer.length);  //将缓存区的字节数写入当前请求流返回
       output.close();
      }
     }));
     subthread.start(requestcontext); //开启处理线程处理下载文件
    }
    catch (exception ex)
    {
     try
     {
      requestcontext.response.statuscode = 500;
      requestcontext.response.contenttype = "application/text";
      requestcontext.response.contentencoding = encoding.utf8;
      byte[] buffer = system.text.encoding.utf8.getbytes("system error");
      //对客户端输出相应信息.
      requestcontext.response.contentlength64 = buffer.length;
      system.io.stream output = requestcontext.response.outputstream;
      output.write(buffer, 0, buffer.length);
      //关闭输出流,释放相应资源
      output.close();
     }
     catch { }
    }
   }
  }

  /// <summary>
  /// 执行其他超做请求监听行为
  /// </summary>
  public static void gethttotherrequest()
  {
   while (true)
   {
    httplistenercontext requestcontext = httotherrequest.getcontext(); //接受到新的请求
    try
    {
     //reecontext 为开启线程传入的 requestcontext请求对象
     thread subthread = new thread(new parameterizedthreadstart((reecontext) =>
     {
      console.writeline("执行其他超做请求监听行为");
      var request = (httplistenercontext)reecontext;
      var msg = httputility.urldecode(request.request.querystring["behavior"]); //接受get请求过来的参数;
      //在此处执行你需要进行的操作>>比如什么缓存数据读取,队列消息处理,邮件消息队列添加等等。

      request.response.statuscode = 200;
      request.response.headers.add("access-control-allow-origin", "*");
      request.response.contenttype = "application/json";
      requestcontext.response.contentencoding = encoding.utf8;
      byte[] buffer = system.text.encoding.utf8.getbytes(jsonconvert.serializeobject(new { success = true, behavior = msg }));
      request.response.contentlength64 = buffer.length;
      var output = request.response.outputstream;
      output.write(buffer, 0, buffer.length);
      output.close();
     }));
     subthread.start(requestcontext); //开启处理线程处理下载文件
    }
    catch (exception ex)
    {
     try
     {
      requestcontext.response.statuscode = 500;
      requestcontext.response.contenttype = "application/text";
      requestcontext.response.contentencoding = encoding.utf8;
      byte[] buffer = system.text.encoding.utf8.getbytes("system error");
      //对客户端输出相应信息.
      requestcontext.response.contentlength64 = buffer.length;
      system.io.stream output = requestcontext.response.outputstream;
      output.write(buffer, 0, buffer.length);
      //关闭输出流,释放相应资源
      output.close();
     }
     catch { }
    }
   }
  }
 }
}

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

using system;
using system.collections.generic;
using system.linq;
using system.text;

namespace httplistenerapp
{
 class program
 {
  static void main(string[] args)
  {
   //开启请求监听
   httpprovider.init();
  }
 }
}

执行后的结果为:

.NET下通过HttpListener实现简单的Http服务

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。