簡易Webサーバー
ここのコードとほぼ同じ。だけどパスの置換とかいらない。
簡易Webサーバを実装するには? - @IT
コード
using System; using System.IO; using System.Net; class SimpleWebserver { static void Main() { string root = "/Users/inohiro/Projects/lab/SimpleWebserver"; // string root = "C:\app"; // for Windows string prefix = "http://*:8080/"; HttpListener listener = new HttpListener(); listener.Prefixes.Add( prefix ); listener.Start(); while( true ) { HttpListenerContext context = listener.GetContext(); HttpListenerRequest req = context.Request; HttpListenerResponse res = context.Response; Console.WriteLine( req.RawUrl ); string path = root + req.RawUrl; // string path = root + req.RawUrl.Replace( "/", "\\" ); // for Windows Console.WriteLine( "{0}", path ); if( File.Exists( path ) ) { byte[] content = File.ReadAllBytes( path ); res.OutputStream.Write( content, 0, content.Length ); } res.Close(); } } }
実行例
inohiro-mac:SimpleWebserver inohiro$ mono main.exe /hello.html /Users/inohiro/Projects/lab/SimpleWebserver/hello.html /favicon.ico /Users/inohiro/Projects/lab/SimpleWebserver/favicon.ico
問題点
権限が。