/// <summary> /// Constructor accepting context that the response will be /// sent back to. /// </summary> public LPWebResponse(LPWebContext context) { Context = context; HeaderSent = false; ContentLength64 = -1; StatusCode = 200; ContentType = "text/html"; }
/// <summary> /// Creates a new context object for a web request /// but reading the data sent to a recently opened /// socket. /// </summary> public static LPWebContext FromSocket(Socket socket) { var ret = new LPWebContext(); ret.ConnectedSocket = socket; ret.Request = LPWebRequest.Read(socket); ret.Response = new LPWebResponse(ret); return(ret); }
/// <summary> /// Reads the request URL and calls the appropriate method /// to send a response. /// </summary> public void HandleRequest(LPWebContext context) { // TODO: add route for requests: // // /settings/midimap // if data posted, update the data // always write out the latest data as a response // // /settings/implants // if data posted, updated the data // always write out all current status of implants // // /settings/hardware // for which midi devices are active, and the names of those available if (context.Request.Path.StartsWith("/settings/")) { if (context.Request.Path.StartsWith("/settings/implants")) { ImplantSettingsAjax.Process(context); } else if (context.Request.Path.StartsWith("/settings/devices")) { DeviceSettingsAjax.Process(context); } else if (context.Request.Path.StartsWith("/settings/midimap")) { MappingSettingsAjax.Process(context); } else if (context.Request.Path.StartsWith("/settings/gui")) { GuiSettingsAjax.Process(context); } else { context.Response.Send500("Invalid settings ajax request: " + context.Request.RawUrl); } return; } else if (context.Request.Path.StartsWith("/logs/")) { LoggingAjax.Process(context); return; } // static file var path = new Util.FilePath() { BaseFolder = WebRoot, Filename = "~" + context.Request.Filename, Source = "WebServer" }; context.Response.SendFile(path); }
/// <summary> /// If there is a pending connection, the request is parsed an /// scheduled to be executed in the kernel. /// </summary> public void SchedulePending() { while (_server.Pending()) { new RequestTask() { Handler = Handler, Context = LPWebContext.FromSocket(_server.AcceptSocket()) }.ScheduleTask(); } }
/// <summary> /// Thread that listens to new requests and starts off tasks /// to send the requests to the OnRequest event. /// </summary> private void WebServerThread() { // from http://www.codeproject.com/Articles/1505/Create-your-own-Web-Server-using-C try { IsListening = true; while (_server != null) { var socket = _server.AcceptSocket(); Task.Factory.StartNew(() => { var ctx = LPWebContext.FromSocket(socket); try { if (OnRequest != null) { OnRequest(this, ctx); } } finally { ctx.Finish(); } }); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { IsListening = false; } }