static void Main(string[] args) { string server_ini_file = @"Ini\servers.ini"; C("HTTP Server Starting"); if (File.Exists(server_ini_file)) { C("Using File {0} for configuration", server_ini_file); FileIniDataParser parser = new FileIniDataParser(); var servers = parser.LoadFile(server_ini_file); servers.Sections .ToList() .ForEach(server_config => { NSServer server = new NSServer(server_config.Keys["listenon"], Int32.Parse(server_config.Keys["port"]), "/"); server.CreateHttpServer(); C("Starting Server {0} : listening on http://{1}:{2}/", server_config.SectionName, server_config.Keys["listenon"], server_config.Keys["port"]); }); C("Servers have been started."); } Console.WriteLine("Waiting..."); Console.Read(); }
/// <summary> /// Basic Http Server (Static Content) /// </summary> public static void CreateHttpServer(this NSServer ns) { Thread t = new Thread(new ThreadStart(() => { Boolean active = true; HttpListener l = new HttpListener(); l.Prefixes.Add(String.Format("http://{0}:{1}/", ns.ListenPath, ns.Port)); l.Start(); while (active) { IAsyncResult result = l.BeginGetContext(new AsyncCallback((asyResult) => { HttpListener listener = (HttpListener)asyResult.AsyncState; HttpListenerContext context = listener.EndGetContext(asyResult); HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; String responseString = "{}"; var url_query = request.Url; string dataset_name = url_query.AbsolutePath.Replace("/", ""); string dataset_file_name = String.Format(@"Cache\{0}.data", dataset_name); if (url_query.AbsolutePath.Contains(".ico")) { return; } if (File.Exists(dataset_file_name)) { var dataset_file = new FileInfo(dataset_file_name); if ((DateTime.Now - dataset_file.LastWriteTime).Minutes >= 10) { File.Delete(dataset_file.FullName); DataAccess access = new DataAccess(true, "default"); var data_result = access.ExecuteSql(string.Format("SELECT * FROM {0}", dataset_name)); responseString = Newtonsoft.Json.JsonConvert.SerializeObject(data_result); access.Dispose(); } else { responseString = File.ReadAllText(dataset_file_name); } } else { // Get the Data and Save it then return it DataAccess access = new DataAccess(true, "default"); var data_result = access.ExecuteSql(string.Format("SELECT * FROM {0}", dataset_name)); responseString = Newtonsoft.Json.JsonConvert.SerializeObject(data_result); access.Dispose(); File.WriteAllText(dataset_file_name, responseString); } Byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString); response.ContentLength64 = buffer.Length; response.ContentType = "application/json"; System.IO.Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); output.Flush(); output.Close(); }), l); result.AsyncWaitHandle.WaitOne(); } })); t.Start(); }