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

所属分类: 网络编程 / ASP.NET 阅读数: 660
收藏 0 赞 0 分享

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();
  }
 }
}

执行后的结果为:

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

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

更多精彩内容其他人还在看

asp.net 虚方法、抽象方法、接口疑问

asp.net 虚方法、抽象方法、接口疑问等说明。
收藏 0 赞 0 分享

c#  操作符?? null coalescing operator

?? "null coalescing" operator 是c#新提供的一个操作符,这个操作符提供的功能是判断左侧的操作数是否是null,如果是则返回结果是右侧的操作数;非null则返回左侧的操作数。
收藏 0 赞 0 分享

.net 反序题目的详细解答第1/2页

在各种答案,以及平时面试过程中,这道题总归会有一些非常典型的错误发生。其中给老赵的感觉也非常有意思,不知其中的“思路”是否如老赵猜测那样。
收藏 0 赞 0 分享

implicitly convert type 'int' to 'short'的原因与解决方法

implicitly convert type 'int' to 'short'的原因与解决方法
收藏 0 赞 0 分享

比较完整的 asp.net 学习流程

好多朋友想学习后台编程语言,但请注意的事,学习后台是个循序渐进的过程,不可能一下就到位,其实不只是asp.net其它的编程语言都需要下面的一些知识。
收藏 0 赞 0 分享

官网 Ext direct包中.NET版的问题

下载了官网的 Ext direct 包进行研究,发现服务器端返回结果存在一点小问题。
收藏 0 赞 0 分享

C# XML操作 代码大全(读XML,写XML,更新,删除节点,与dataset结合等)第1/2页

C#操作XML(读XML,写XML,更新,删除节点,与dataset结合等),以下就是操作XML的所有方法,相信可以满足很大一部份的使用了。
收藏 0 赞 0 分享

c# 连接字符串数据库服务器端口号 .net状态服务器端口号

正常的数据库连接字符串配置,这是在MSSQL服务器端口是1433(默认)的情况下。
收藏 0 赞 0 分享

ASP.NET 路径问题的解决方法

相对路径和绝对路径在ASP.NET中可以用~/来解决.
收藏 0 赞 0 分享

asp.net TemplateField模板中的Bind方法和Eval方法

在TemplateField模板中为了能够有限制的或者取出数据库中某列的值时,可以用Bind和Eval方法来实现。以下是Bind方法的格式,Eval的格式也是和Bind一样的。 Bind("列的名称","显示的格式文")
收藏 0 赞 0 分享
查看更多