通過HttpListener實現簡單的Http服務

来源:http://www.cnblogs.com/heyangyi/archive/2016/09/02/5832869.html
-Advertisement-
Play Games

使用HttpListener實現簡單的Http服務 HttpListener提供一個簡單的、可通過編程方式控制的 HTTP 協議偵聽器.使用它可以很容易的提供一些Http服務,而無需啟動IIS這類大型服務程式。使用HttpListener的方法流程很簡單:主要分為以下幾步 創建一個HTTP偵聽器對象 ...


使用HttpListener實現簡單的Http服務

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接收到請求後就立即返回,交給隊列去發送郵件。郵件的發送會出現延遲等待等情況出現,這樣就不用等待。等等
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 在一些複雜的Linux維護工作中,大量重覆的輸入和交互操作不但費時費力,容易出錯.這時候就需要用到腳本。 編寫腳本的好處: 批量的處理,自動化的完成維護,減輕管理員的負擔。 linux的shell腳本是一種特殊的應用程式,常見的shell解釋器有很多種,使用不同的shell時期內部指令:cat /e ...
  • LVS介紹 lvs 核心ipvs Ipvs(IP Virtual Server)是整個負載均衡的基礎,如果沒有這個基礎,故障隔離與失敗切換就毫無意義了。Ipvs 具體實現是由ipvsadm 這個程式來完成,因此判斷一個系統是否具備ipvs 功能,只需要察看ipvsadm 程式是否被安裝。察看ipvs ...
  • 1. 安裝libevent 2. 安裝memcached 3. 安裝memagent 3-1。修改Makefile 3-2。修改ketama.h 3-3.安裝memagent 1 make 2 ln -i /usr/local/magent/magent /usr/bin/magent 4. 使用m ...
  • 1.U-Boot,全稱 Universal Boot Loader,是遵循GPL條款的開放源碼項目。U-Boot的作用是系統引導。U-Boot從FADSROM、8xxROM、PPCBOOT逐步發展演化而來。其源碼目錄、編譯形式與Linux內核很相似,事實上,不少U-Boot源碼就是根據相應的Linu ...
  • ...
  • There are commonly three types of memories in a PIC Microcontroller, Flash Program Memory, Data Memory (RAM) and EEPROM Data Memory. We write Programs... ...
  • Ubuntu 16.04系統在一開始安裝完成時是無法切換到 root 用戶的,普通用戶需要使用 root 許可權的時候通常需要在執行命令前加 "sudo",需要經常使用root許可權的伙伴可能會覺得這會讓我們的蛋蛋同學很憂傷...... 其實,要解決蛋蛋同學的問題很簡單,只要給 root 配一個密碼即可 ...
  • 整理Apache+Mysql+PHP+PHPWind(Apache+PHP集成環境) 一、情況簡述: 1、虛擬機VM上面CentOS 2、全部yum安裝(yum安裝與源碼安裝的安裝路徑不同) 二、操作步驟簡述 安裝Apache(httpd) 安裝Mysql(mysqld) 安裝PHP(phpd-fd ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...