Implementing simple Http service through HttpListener under .NET

黄舟
Release: 2017-02-22 10:35:21
Original
4213 people have browsed it

HttpListener provides a simple, programmatically controllable HTTP protocol listener. It can easily provide some Http services without starting a large service program such as IIS. The process of using HttpListener is very simple: it is mainly divided into the following steps

1. Create an HTTP listener object and initialize

2. Add the URI prefix that needs to be listened to

3. Start listening for requests from the client

4. Process the client’s Http request

5. Close the HTTP listener

For example: We want to implement a simple Http service, download files, or perform some other operations, such as sending emails, using HttpListener to listen, processing the email queue, and avoiding synchronization waiting on the website. And get some cached data and other behaviors

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 { }
    }
   }
  }
 }
}
Copy after login



Calling method: Note that the startup program here must be run as an administrator, because the morning monitoring needs to open the port. All need to be run as administrator.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HttpListenerApp
{
 class Program
 {
  static void Main(string[] args)
  {
   //开启请求监听
   HttpProvider.Init();
  }
 }
}
Copy after login



The result after execution is:

Implementing simple Http service through HttpListener under .NET

It is used here through a simple control program HttpListener implements a simple Http service program. There are a small number of threads and asynchronous processing. For example, when a behavioral information request is received, it can be returned to the user first, so that the user can perform the next operation without waiting synchronously. Another example is the implementation of a simple mail server that sends the request to HttpListener to receive it. It returns immediately after the request and leaves it to the queue to send the email. There may be delays in sending emails, so there is no need to wait.

The above is the content of implementing simple Http service through HttpListener under .NET. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!