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.Threading.Tasks;
public class HttpServer : IDisposable
{
private const string NotFoundResponse = "<!doctype html><html><body>Resource not found</body></html>";
private readonly HttpListener httpListener;
private readonly CancellationTokenSource cts = new CancellationTokenSource();
private readonly string prefixPath; private Task processingTask; public HttpServer(string listenerUriPrefix)
{
this.prefixPath = ParsePrefixPath(listenerUriPrefix);
this.httpListener = new HttpListener();
this.httpListener.Prefixes.Add(listenerUriPrefix);
} private static string ParsePrefixPath(string listenerUriPrefix)
{
var match = Regex.Match(listenerUriPrefix, @"http://(?:[^/]*)(?:\:\d+)?/(.*)");
if (match.Success)
{
return match.Groups[1].Value.ToLowerInvariant();
}
else
{
return string.Empty;
}
} public void Start()
{
this.httpListener.Start();
this.processingTask = Task.Factory.StartNew(async () => await ProcessRequests(), TaskCreationOptions.LongRunning);
} private async Task ProcessRequests()
{
while (!this.cts.IsCancellationRequested)
{
try
{
var context = await this.httpListener.GetContextAsync();
try
{
await ProcessRequest(context).ConfigureAwait(false);
context.Response.Close();
}
catch (Exception ex)
{
context.Response.StatusCode = 500;
context.Response.StatusDescription = "Internal Server Error";
context.Response.Close();
Console.WriteLine("Error processing HTTP request\n{0}", ex);
}
}
catch (ObjectDisposedException ex)
{
if ((ex.ObjectName == this.httpListener.GetType().FullName) && (this.httpListener.IsListening == false))
{
return; // listener is closed/disposed
}
Console.WriteLine("Error processing HTTP request\n{0}", ex);
}
catch (Exception ex)
{
HttpListenerException httpException = ex as HttpListenerException;
if (httpException == null || httpException.ErrorCode != 995)// IO operation aborted
{
Console.WriteLine("Error processing HTTP request\n{0}", ex);
}
}
}
} private Task ProcessRequest(HttpListenerContext context)
{
if (context.Request.HttpMethod.ToUpperInvariant() != "GET")
{
return WriteNotFound(context);
} var urlPath = context.Request.RawUrl.Substring(this.prefixPath.Length)
.ToLowerInvariant(); switch (urlPath)
{
case "/":
if (!context.Request.Url.ToString().EndsWith("/"))
{
context.Response.Redirect(context.Request.Url + "/");
context.Response.Close();
return Task.FromResult(0);
}
else
{
return WriteString(context, "Hello World!", "text/plain");
}
case "/favicon.ico":
return WriteFavIcon(context);
case "/ping":
return WritePong(context);
}
return WriteNotFound(context);
} private static Task WritePong(HttpListenerContext context)
{
return WriteString(context, "pong", "text/plain");
} private static async Task WriteFavIcon(HttpListenerContext context)
{
context.Response.ContentType = "image/png";
context.Response.StatusCode = 200;
context.Response.StatusDescription = "OK";
using (var stream = File.Open("icon.png", FileMode.Open))
{
var output = context.Response.OutputStream;
await stream.CopyToAsync(output);
}
} private static Task WriteNotFound(HttpListenerContext context)
{
return WriteString(context, NotFoundResponse, "text/plain", 404, "NOT FOUND");
} private static async Task WriteString(HttpListenerContext context, string data, string contentType,
int httpStatus = 200, string httpStatusDescription = "OK")
{
AddCORSHeaders(context.Response);
AddNoCacheHeaders(context.Response); context.Response.ContentType = contentType;
context.Response.StatusCode = httpStatus;
context.Response.StatusDescription = httpStatusDescription; var acceptsGzip = AcceptsGzip(context.Request);
if (!acceptsGzip)
{
using (var writer = new StreamWriter(context.Response.OutputStream, Encoding.UTF8, 4096, true))
{
await writer.WriteAsync(data).ConfigureAwait(false);
}
}
else
{
context.Response.AddHeader("Content-Encoding", "gzip");
using (GZipStream gzip = new GZipStream(context.Response.OutputStream, CompressionMode.Compress, true))
using (var writer = new StreamWriter(gzip, Encoding.UTF8, 4096, true))
{
await writer.WriteAsync(data).ConfigureAwait(false);
}
}
} private static bool AcceptsGzip(HttpListenerRequest request)
{
string encoding = request.Headers["Accept-Encoding"];
if (string.IsNullOrEmpty(encoding))
{
return false;
} return encoding.Contains("gzip");
} private static void AddNoCacheHeaders(HttpListenerResponse response)
{
response.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate");
response.Headers.Add("Pragma", "no-cache");
response.Headers.Add("Expires", "0");
} private static void AddCORSHeaders(HttpListenerResponse response)
{
response.Headers.Add("Access-Control-Allow-Origin", "*");
response.Headers.Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
} private void Stop()
{
cts.Cancel();
if (processingTask != null && !processingTask.IsCompleted)
{
processingTask.Wait();
}
if (this.httpListener.IsListening)
{
this.httpListener.Stop();
this.httpListener.Prefixes.Clear();
}
} public void Dispose()
{
this.Stop();
this.httpListener.Close();
using (this.cts) { }
using (this.httpListener) { }
}
}

利用HttpListener创建简单的HTTP服务的更多相关文章

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

    使用HttpListener实现简单的Http服务 HttpListener提供一个简单的.可通过编程方式控制的 HTTP 协议侦听器.使用它可以很容易的提供一些Http服务,而无需启动IIS这类大型 ...

  2. 1.WCF学习--创建简单的WCF服务

    一.基本了解WCF 1.面向服务代表的是一种设计理念,和面向对象.面向组件一样,体现的是一种对关注点进行分解的思想,面向服务是和技术无关的 2.WCF需要依存一个运行着的宿主进程,服务寄宿就是为服务指 ...

  3. 利用WCF创建简单的RESTFul Service

    1):用VS2013创建一个WCF的工程,如下图所示: 2):我们来看一下默认状态下的config文件内容,这里的内容我们会再后续的步骤中进行修改 <?xml version="1.0 ...

  4. 使用C#创建简单的WCF服务

    一.开发环境 操作系统:Windows 10 开发环境:VS2015 编程语言:C# IIS版本:10.0.0.0 二.添加WCF服务.Internet Information Services(II ...

  5. 使用nomad && consul && fabio 创建简单的微服务系统

    具体每个组件的功能就不详细说明了 nomad 一个调度工具,consul 一个服务发现,健康检查多数据中心支持的工具 fabio 一个基于consul的负载均衡&&动态路由工具,对于集 ...

  6. 通过VS创建简单的WCF服务

    http://www.cnblogs.com/artech/archive/2007/09/15/893838.html http://www.topwcftutorials.net/2013/09/ ...

  7. 使用idea创建简单的webservice服务

     New project: 生成HelloWorld.wsdl: 配置好tomcat后还需要加入 Axis 的库: 启动后,访问http://localhost:8080/services: 点击He ...

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

    很多时候都在讨论是否需要了解一个组件或者一个语言的底层原理这个问题,其实我个人觉得,对于这个问题,每个人都有自己的看法,个人情况不同,选择的方式也就会不同了.我个人觉得无论学习什么,都应该尝试着去了解 ...

  9. c# 通过HttpListener创建HTTP服务

    在c#中可以利用HttpListener来自定义创建HTTP服务,通过http协议进行服务端与多个客户端之间的信息传递,并且可以做成windows系统服务,而不用寄宿在IIS上.以下为一个demo,分 ...

随机推荐

  1. 由SimpleAyncTaskExecutor到ListenableFutureTask

    Spring AsyncExecutor观后感 导语 本来想看下spring关于Async&Sync TaskExecutor的主要内容,看着看着发现ListenableTaskExecuto ...

  2. SharePoint 2013 列表多表联合查询

    在SharePoint的企业应用中,遇到复杂的逻辑的时候,我们会需要多表查询:SharePoint和Sql数据表一样,也支持多表联合查询,但是不像Sql语句那样简单,需要使用SPQuery的Joins ...

  3. 如何通过PowerShell在Visual Studio的Post-build中预热SharePoint站点

    问题现象 Visual Studio在开发SharePoint的时候,发布部署包后,首次打开及调试站点页面的时候会非常的慢 解决方案 使用PowerShell脚本,加载SharePoint插件后遍历所 ...

  4. C标准库<ctype.h>实现

    本文地址:http://www.cnblogs.com/archimedes/p/c-library-ctype.html,转载请注明源地址. 1.背景知识 ctype.h是C标准函数库中的头文件,定 ...

  5. Spring(九)Spring对事务的支持

    一.对事务的支持 事务:是一组原子操作的工作单元,要么全部成功,要么全部失败 Spring管理事务方式: JDBC编程事务管理:--可以控制到代码中的行 可以清楚的控制事务的边界,事务控制粒度化细(编 ...

  6. java网络---查找Internet

    连接到Internet的设备称为节点,计算机节点称为host. 为了区别每一台连接互联网的计算机,就有了Internet Protocol地址的概念. IPV4 & IPV6 我们以前默认的是 ...

  7. Mysql中的视图

    什么是视图 通俗的讲,视图就是一条SELECT语句执行后返回的结果集.所以我们在创建视图的时候,主要的工作就落在创建这条SQL查询语句上. 视图的特性 视图是对若干张基本表的引用,一张虚表,查询语句执 ...

  8. linux 查看系统版本

    博客分类: linux LinuxRedHatDebianSuSE  几种查看linux版本信息的方法: uname -a cat /proc/version cat /etc/issue lsb_r ...

  9. .NET 反射的使用

    1.根据类名获取类实例 string className = "Company.BigProgram.BLL.TestClass"; Type type = Type.GetTyp ...

  10. Linux运维工程师入门须掌握的10个技术点

    本人是linux运维工程师,对这方面有点心得,现在我说说要掌握哪方面的工具吧 说到工具,在行外可以说是技能,在行内我们一般称为工具,就是运维必须要掌握的工具. 我就大概列出这几方面,这样入门就基本没问 ...