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. 状态压缩DP---Hie with the Pie

    http: //acm.hust.edu.cn/vjudge/contest/view.action?cid=110044#problem/B Description The Pizazz Pizze ...

  2. KMP--Simpsons’ Hidden Talents

    题目网址:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=110060#problem/C Description Homer: Marge ...

  3. Scala on Visual Studio Code

    Download and install Scala Download a scala installation package from here. Then install it. Linux s ...

  4. Hibernate中的脏检查和缓存清理机制

    脏检查 Session到底是如何进行脏检查的呢?当一个Customer对象被加入到Session缓存中时,Session会为Customer对象的值类型的属性复制一份快照.当Session清理缓存时, ...

  5. vundle按照YouComplete

    https://github.com/VundleVim/Vundle.vim http://www.jianshu.com/p/d908ce81017a?nomobile=yes http://ww ...

  6. SharePoint 2013 - User

    1. 在SharePoint 2010中,可以搜索出NT AUTHORITY\authenticated users,但在SharePoint 2013中,不能搜索出,需要手动写入全名后进行验证: 2 ...

  7. Purchase购物车实例分析

    源代码下载地址:http://code4app.com/ios/55655def933bf09d328b5141 此源代码从中学到以下四个知识点 第一:关于右边只有一个被选中的效果展现,左边部分代码内 ...

  8. iOS 核心动画

    核心动画(Core Animation) : •CoreAnimation是一组非常强大的动画处理API,使用它能做出非常炫丽的动画效果,而且往往是事半功倍,使用它需要先添加QuartzCore.fr ...

  9. ios开发随笔第一篇-button,label按钮的一些属性的使用

    我用的是纯代码方式,喜欢用storyboard开发的其实也很爽了; 首先谈谈button,ios中新建button这个对象一般接触的都明白,UIButton *button名=[ UIButton a ...

  10. iOS开发中的一些定时器

    在软件开发过程中,我们常常需要在某个时间后执行某个方法,或者是按照某个周期一直执行某个方法.在这个时候,我们就需要用到定时器. 然而,在iOS中有很多方法完成以上的任务,到底有多少种方法呢?经过查阅资 ...