教学小例子:简易的webSevrer
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的更多相关文章
- javascript平时小例子⑥(简易计算器的制作)
<!doctype html><html><head><meta charset="utf-8"><title>无标题文 ...
- HTML5 Canvas 小例子 简易画板
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- WebService小例子———
WebService学习(刚开始) ———————————————————————————————————————————————————————————————————— WebService:跨平 ...
- springmvc入门的第一个小例子
今天我们探讨一下springmvc,由于是初学,所以简单的了解一下 springmvc的流程,后续会持续更新... 由一个小例子来简单的了解一下 springmvc springmvc是spring框 ...
- java即时通信小例子
学习java一段时间了,今天写来一个即时通信的小例子练手在其过程中也学到了一些知识拿出来和大家分享,请路过的各位大神多多赐教... 好了下面讲一下基本的思路: 首先,编写服务器端的程序,简单点说吧就是 ...
- Runtime的几个小例子(含Demo)
一.什么是runtime(也就是所谓的“运行时”,因为是在运行时实现的.) 1.runtime是一套底层的c语言API(包括很多强大实用的c语言类型,c语言函数); [runti ...
- bootstrap 模态 modal 小例子
bootstrap 模态 modal 小例子 <html> <head> <meta charset="utf-8" /> <title ...
- INI配置文件分析小例子
随手写个解析INI配置字符串的小例子 带测试 #include <iostream> #include <map> #include <string> #inclu ...
- JavaScript小例子:复选框全选
JavaScript小例子:复选框全选 这只是一个小例子,很简单,但是这个功能还是很常用的: 实现后效果如图: JavaScript代码: <script type="text/jav ...
随机推荐
- 伞兵(Paratroopers)
伞兵(Paratroopers) 时间限制: 1 Sec 内存限制: 128 MB 题目描述 公元 2500 年,地球和火星之间爆发了一场战争.最近,地球军队指挥官获悉火星入侵者将派一些伞兵来摧毁地 ...
- ORA-00245问题总结
(1)问题描述 在进行数据库归档备份时(备份归档日志文件和控制文件),有时成功,有时失败,失败报错如下: RMAN-00571: =================================== ...
- 关于JS数组的定义
关于js数组的定义的一些内容: 数组是一个对象 只用一个变量,储存多个同类型的信息 数组--连续的储存空间 数组的下标从0开始 ps:定义一个数组可以看作是一个旅馆.里面有很多小房子. 1.创建数组- ...
- Jenkins插件开发
一.环境配置 不赘述,直接看wiki:https://wiki.jenkins.io/display/JENKINS/Extend+Jenkins 二.内容说明 1.插件代码结构 src/main/j ...
- 一个"2-SUM"问题
题目要求: Download the text file here. (Right click and save link as). The goal of this problem is to im ...
- Backbone中父子view之间的值传递
backbone中,使用最多的莫过于在view中进行操作,如模板的渲染以及事件函数的定义.为了提高代码的可维护性,一般地我们会写多个视图即view,将界面按照功能的不同进行模块化划分,模块与view一 ...
- 解决java.lang.NumberFormatException: For input string: "id"
今天,项目突然报"java.lang.NumberFormatException:For input string:"id"",项目框架是spring,spri ...
- Linux配置LNMP环境(二)配置PHP
前言:本教程安装的PHP版本php-5.6.30(官方最后更新日期2017-01-19),教程编写日期2017-07-02.本教程中的下载地址是在写教程的时候从官方复制的,时间过长可能会有变化. 安装 ...
- database.properties数据源
jdbc.driver_class=oracle.jdbc.driver.OracleDriverjdbc.connection.url=jdbc:oracle:thin:@localhost:152 ...
- windows安装程序无法将windows配置为在此计算机的硬件上运行
关于装windows系统时,出现一些安装中断的处理 该方法适用于 windows安装程序无法将windows配置为在此计算机的硬件上运行 计算机意外地重新启动或遇到错误. Windows 安装无法继续 ...