通过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接收到请求后就立即返回,交给队列去发送邮件。邮件的发送会出现延迟等待等情况出现,这样就不用等待。等等

时间: 2024-08-07 06:14:30

通过HttpListener实现简单的Http服务的相关文章

利用HttpListener创建简单的HTTP服务

using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.

一个简单的WCF服务

以订票为例简单应用wcf程序,需要的朋友可以参考下 WCF实例(带步骤) 复制代码代码如下: <xmlnamespace prefix ="o" ns ="urn:schemas-microsoft-com:office:office" /> 本篇转自百度文档,自己试过,确实可以用. 以订票为例简单应用wcf 新建一个wcf服务应用程序 在IService1.cs定义服务契约 复制代码代码如下: namespace WcfDemo { // 注意: 如果

WCF--建立简单的WCF服务

在VS2010里建立一个最简单的WCF服务,基本流程如下: 一:新建WCF应用 首先,新建一个WCF服务的应用,如下图所示 建立完成之后,VS将自动生成一个最简单的WCF工程,在这个应用中,包含了最基本Contract.Service. 工程如下: 不需要编辑任何文件,直接编译生成,得到一个WcfService1.dll文件 二.WCF应用中的契约(Contract) 在生成的WCF工程中,IService1.cs中为Contract(本例中契约和服务放在同一个工程下了,实际上也可以分为两个工程

构建简单的 C++ 服务组件,第 1 部分: 服务组件体系结构 C++ API 简介

构建简单的 C++ 服务组件,第 1 部分: 服务组件体系结构 C++ API 简介 熟悉将用于 Apache Tuscany SCA for C++ 的 API.您将通过本文了解该 API 的主要组成部分,以便快速入门. 查看本系列更多内容 | 0 评论: Ed Slattery ([email protected]), 软件工程师, IBM UK Pete Robbins ([email protected]), 软件工程师, IBM UK Andrew Borley ([email pro

树莓派(Raspberry Pi)搭建简单的lamp服务

树莓派(Raspberry Pi)搭建简单的lamp服务: 1. LAMP 的安装 sudo apt-get install apache2 mysql-server mysql-client php5 php5-gd php5-mysql –安装mysql.apache.php sudo chmod 777 /var/www/ –设置web目录的权限 2. phpmyadmin 安装 sudo apt-get install phpmyadmin –安装后选择apache2 3.配置 sudo

Netty4.0学习笔记系列之三:构建简单的http服务(转)

http://blog.csdn.net/u013252773/article/details/21254257 本文主要介绍如何通过Netty构建一个简单的http服务. 想要实现的目的是: 1.Client向Server发送http请求. 2.Server端对http请求进行解析. 3.Server端向client发送http响应. 4.Client对http响应进行解析. 在该实例中,会涉及到http请求的编码.解码,http响应的编码.解码,幸运的是,Netty已经为我们提供了这些工具,

简单消息队列服务 HTTPSQS

HTTPSQS(HTTP?Simple?Queue?Service)是一款基于 HTTP GET/POST 协议的轻量级开源简单消息队列服务,使用 Tokyo Cabinet 的 B+Tree Key/Value 数据库来做数据的持久化存储. 队列(Queue)又称先进先出表(First In First Out),即先进入队列的元素,先从队列中取出.加入元素的一头叫"队头",取出元素的一头叫"队尾".利用消息队列可以很好地异步处理数据传送和存储,当你频繁地向数据库

使用Topshelf组件构建简单的Windows服务

很多时候都在讨论是否需要了解一个组件或者一个语言的底层原理这个问题,其实我个人觉得,对于这个问题,每个人都有自己的看法,个人情况不同,选择的方式也就会不同了.我个人觉得无论学习什么,都应该尝试着去了解对应的原理和源码(这里就不要急着吐槽,容我说完).对底层的了解不是为了让你写出类似的东西,让你写也不可能写的出来,重写一个就需要以此修改整个底层结构,了解底层知识只是为了让你可以在写业务代码时,选择合适的方式,以此使底层与业务层配合达到效率最佳.任何一种方式有坏有好,需要合适的选择. 如果觉得楼主以

利用SpringCloud搭建一个最简单的微服务框架

http://blog.csdn.net/caicongyang/article/details/52974406 1.微服务 微服务主要包含服务注册,服务发现,服务路由,服务配置,服务熔断,服务降级等一系列的服务,而Spring Cloud为我们提供了个一整套的服务: 本例子为你提供了最简单的一个服务发现例子,包含服务注册发现spingCloudEurekaServer.服务配置中心spingCloudConfServer.以及一个app应用springCloudApp 2.服务注册与发现 s