using System; using System.Net; using System.Collections.Generic; using System.Threading; namespace TDPC { public class WebServer { public event EventHandler IsUp; public delegate byte[] ResourceProvider(); HttpListener listener_; string definition_; Dictionary resources_; Thread thread_; public WebServer( string definition ) { listener_ = new HttpListener(); listener_.Prefixes.Add(definition); definition_ = definition; resources_ = new Dictionary(); } public void AddResource( string path, ResourceProvider provider ) { resources_[definition_+path] = provider; } public void Start() { thread_ = new Thread(new ThreadStart(ServerMain)); thread_.Start(); if( IsUp == null ) return; IsUp(this,null); } public void Stop() { if( thread_ != null ) thread_.Abort(); listener_.Stop(); } void ServerMain() { listener_.Start(); for(;;) { HttpListenerContext context = listener_.GetContext(); HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; byte[] buffer; try { buffer = resources_[request.Url.OriginalString].Invoke(); } catch( KeyNotFoundException ) { response.StatusCode = 404; buffer = System.Text.Encoding.UTF8.GetBytes("Resource not found"); } response.ContentLength64 = buffer.Length; System.IO.Stream output = response.OutputStream; output.Write(buffer,0,buffer.Length); output.Close(); } } } }