當前位置:
首頁 > 知識 > 教學小例子:簡易的webSevrer

教學小例子:簡易的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

教學小例子:簡易的webSevrer

教學小例子:簡易的webSevrer

喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 達人科技 的精彩文章:

自己動手實現OpenGL-OpenGL原來如此簡單(三)
thinkphp實現無限級分類
Security5:授予許可權
spring boot 項目筆記2一自定義配置文件的讀取
Linux常用命令——顯示文件列表

TAG:達人科技 |

您可能感興趣

《Somewhere Over The Rainbow》尤克里里彈唱教學
KickerTrick-小胖弧面教學之 Tail Stall Revert
《死或生6》Offensive Holds操作教學
一座銹跡斑斑的教學樓 獲獎無數 The Story of Deep Red CorTen Steel
KickerTrick 滑板教學-Halfcab Rock『n』Roll
基於Swift 5的編程教學Swift Playgrounds即將推出
教學 Headstall
Oasis《Don t Look Back In Anger》吉他演奏教學!
將英語閱讀教學的Guided Reading和Literature Circle借鑒到語文閱讀教學中
手機攝影:Snapseed、Enlight製作雙重曝光效果教學
教學樓的freestyle,你見過嗎
日常情侶拍照教學!The Weeknd和Bella Hadid公開秀恩愛!
易烊千璽的原創英文單曲,《nothing to lose》舞蹈教學
想結合日常生活對小朋友進行英語教學?試試這套《Talk To Your Child In English》
街頭時裝教學指南!本周Supreme x Jean Paul Gaultier聯乘穿搭你看如何?
ikon不是ikun,回歸非主打《rubber band》舞蹈教學
Yinterview | 我們強行送一位拉拉去參加Drag Queen變裝教學了
ViewSonic與Boclips達成戰略合作,通過視頻輔助教學
艾弗森Crossover教學
Michael I.Jordan:或許該對 AI 教學進行一些思考