HttpListener 流利简单的API

static void Main()
{
using (var server = new SimpleWebServer("http://localhost:12345/", @"D:/webroot"))
{ Console.WriteLine("http服务开始监听......"); server.Start(); while (true)
{
var inStr = Console.ReadLine(); Debug.Assert(inStr != null, "inStr != null");
if (inStr.Equals("STOP", StringComparison.OrdinalIgnoreCase))
{
break;
}
Console.WriteLine("输入 stop 可停止服务!");
}
}
} public class SimpleWebServer : IDisposable
{ private readonly HttpListener _httpListener; private readonly string _baseFolder; public SimpleWebServer(string uriPrefix, string baseFloder)
{
_httpListener = new HttpListener();
_httpListener.Prefixes.Add(uriPrefix);
_baseFolder = baseFloder;
} public async void Start()
{
_httpListener.Start(); while (true)
{
try
{
var context = await _httpListener.GetContextAsync();
#pragma warning disable 4014
Task.Factory.StartNew(() =>{
PrcessRequestAsync(context);
}); }
catch (HttpListenerException exception)
{
Console.WriteLine(exception);
break;
}
catch (InvalidOperationException exception)
{
Console.WriteLine(exception); break;
}
}
} private async void PrcessRequestAsync(HttpListenerContext context)
{
try
{
string filename = Path.GetFileName(context.Request.RawUrl); // ReSharper disable once AssignNullToNotNullAttribute
string path = Path.Combine(_baseFolder, filename); byte[] msg = new byte[0];
if (File.Exists(path))
{
if (context.Request.HttpMethod == "GET")
{
context.Response.StatusCode = (int) HttpStatusCode.OK;
msg = File.ReadAllBytes(path);
}
else if (context.Request.HttpMethod=="POST")
{
context.Response.StatusCode = (int)HttpStatusCode.Created; }
else
{
context.Response.StatusCode = (int) HttpStatusCode.HttpVersionNotSupported;
} }
else
{
Console.WriteLine($"资源不存在:{path}"); context.Response.StatusCode = (int) HttpStatusCode.NotFound; msg = Encoding.Default.GetBytes(" ...你网址打错了... ");
} context.Response.ContentLength64 = msg.Length; using (Stream s = context.Response.OutputStream)
{
await s.WriteAsync(msg, 0, msg.Length); }
}
catch (Exception exception)
{
Console.WriteLine($"请求发生了错误:{exception}");
}
} public void Dispose()
{
_httpListener.Stop();
}
}

效果:

教学小例子:简易的webSevrer的更多相关文章

  1. javascript平时小例子⑥(简易计算器的制作)

    <!doctype html><html><head><meta charset="utf-8"><title>无标题文 ...

  2. HTML5 Canvas 小例子 简易画板

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  3. WebService小例子———

    WebService学习(刚开始) ———————————————————————————————————————————————————————————————————— WebService:跨平 ...

  4. springmvc入门的第一个小例子

    今天我们探讨一下springmvc,由于是初学,所以简单的了解一下 springmvc的流程,后续会持续更新... 由一个小例子来简单的了解一下 springmvc springmvc是spring框 ...

  5. java即时通信小例子

    学习java一段时间了,今天写来一个即时通信的小例子练手在其过程中也学到了一些知识拿出来和大家分享,请路过的各位大神多多赐教... 好了下面讲一下基本的思路: 首先,编写服务器端的程序,简单点说吧就是 ...

  6. Runtime的几个小例子(含Demo)

    一.什么是runtime(也就是所谓的“运行时”,因为是在运行时实现的.)           1.runtime是一套底层的c语言API(包括很多强大实用的c语言类型,c语言函数);  [runti ...

  7. bootstrap 模态 modal 小例子

    bootstrap 模态 modal  小例子 <html> <head> <meta charset="utf-8" /> <title ...

  8. INI配置文件分析小例子

    随手写个解析INI配置字符串的小例子 带测试 #include <iostream> #include <map> #include <string> #inclu ...

  9. JavaScript小例子:复选框全选

    JavaScript小例子:复选框全选 这只是一个小例子,很简单,但是这个功能还是很常用的: 实现后效果如图: JavaScript代码: <script type="text/jav ...

随机推荐

  1. OCI(Open Container Initiative) & OCF (Open Container Format)

    Linux基金会于2015年6月成立OCI(Open Container Initiative)组织,旨在围绕容器格式和运行时制定一个开放的工业化标准. 开放容器格式标准(OCF, Open Cont ...

  2. Ubuntu16.04更换漂亮绚丽flatabulous主题

    作者:tongqingliu 转载请注明出处: Ubuntu16.04更换漂亮绚丽flatabulous主题 更新 sudo apt-get update sudo apt-get upgrade 安 ...

  3. sharepoint rest api 创建文档库 文件夹

    function createFolder() { var requestHeaders = { "Accept": "application/json;odata=ve ...

  4. head first python helloword

    如何使用python 打出hello word 在python shell 键入print 'hello word'( python 2) or  print ("hello word&qu ...

  5. 如何给两个swiper建立关系

    单个swiper已经满足不了需求了. 各种花式轮播已经慢慢进入市场.swiper该如何立足,那么请看. <div class="swiper-container"> & ...

  6. mongodb取出最大值与最小值

    $res=self::aggregate([ ['$match'=>[ 'msg_id'=>1007, 'D'=>16, ]], ['$group'=>[ '_id'=> ...

  7. css清除浮动float

    css清除浮动float 1.分析HTML代码 <div class="outer"> <div class="div1">1</ ...

  8. 一个"2-SUM"问题

    题目要求: Download the text file here. (Right click and save link as). The goal of this problem is to im ...

  9. 11.page,pagcontext,config对象

  10. htm5拖放和画布

    拖放 拖放是一种常见的特性,即抓取对象以后拖到另一个位置. 在 HTML5 中,拖放是标准的一部分,任何元素都能够拖放. 首先,为了使元素可拖动,把 draggable 属性设置为 true ondr ...