.NET에서 HttpListener를 통해 간단한 Http 서비스 구현

黄舟
풀어 주다: 2017-02-22 10:35:21
원래의
4179명이 탐색했습니다.

HttpListener는 간단하고 프로그래밍 방식으로 제어 가능한 HTTP 프로토콜 수신기를 제공합니다. 이를 사용하면 IIS와 같은 대규모 서비스 프로그램을 시작하지 않고도 일부 HTTP 서비스를 쉽게 제공할 수 있습니다. 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에 보내는 간단한 메일 서버는 요청 직후에 반환되어 이메일을 보내기 위해 대기열에 남겨둡니다. 이메일 발송이 지연될 수 있으므로 기다리실 필요가 없습니다.

위 내용은 .NET에서 HttpListener를 통해 간단한 Http 서비스를 구현한 내용입니다. 더 많은 관련 내용은 PHP 중국어 홈페이지(www.php.cn)를 참고해주세요!

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!