using System; using System.Collections.Generic; using System.Net; using System.Text; using System.Threading; using UnityEngine; namespace AllocsFixes.NetConnections.Servers.Web { public class Web : IServer { private readonly HttpListener _listener = new HttpListener (); private Dictionary handlers = new Dictionary (); public Web (int port) { try { if (!HttpListener.IsSupported) throw new NotSupportedException ("Needs Windows XP SP2, Server 2003 or later."); handlers.Add ("/index.", new SimpleRedirectHandler ("/static/index.html")); handlers.Add ("/static/", new StaticHandler ("/static/", Application.dataPath + "/../webserver", true)); handlers.Add ("/map/", new StaticHandler ("/map/", StaticDirectories.GetSaveGameDir () + "/map", false)); _listener.Prefixes.Add (String.Format ("http://*:{0}/", port)); _listener.Start (); ThreadPool.QueueUserWorkItem ((o) => { try { while (_listener.IsListening) { ThreadPool.QueueUserWorkItem ((c) => { var ctx = c as HttpListenerContext; HandleRequest (ctx.Request, ctx.Response); }, _listener.GetContext ()); } } catch { } } ); Log.Out ("Started Webserver on " + port); } catch (Exception e) { Log.Out ("Error in Web.ctor: " + e); } } private void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp) { try { resp.ProtocolVersion = new Version ("1.1"); if (req.Url.AbsolutePath.Length < 2) { handlers ["/index."].HandleRequest (req, resp); return; } else { foreach (KeyValuePair kvp in handlers) { if (req.Url.AbsolutePath.StartsWith (kvp.Key)) { kvp.Value.HandleRequest (req, resp); return; } } } Log.Out ("Error in Web.HandleRequest(): No handler found for path \"" + req.Url.AbsolutePath + "\""); resp.StatusCode = (int)HttpStatusCode.NotFound; // byte[] buf = Encoding.UTF8.GetBytes ("Hello World"); // resp.ContentLength64 = buf.Length; // resp.ContentType = "text/html"; // resp.ContentEncoding = Encoding.UTF8; // resp.OutputStream.Write (buf, 0, buf.Length); } catch { } finally { resp.Close (); } } public void Disconnect () { try { _listener.Stop (); _listener.Close (); } catch (Exception e) { Log.Out ("Error in Web.Disconnect: " + e); } } public void WriteToClient (string line) { try { Log.Out ("NOT IMPLEMENTED: Web.WriteToClient"); } catch (Exception e) { Log.Out ("Error in Web.WriteToClient: " + e); } } public void WriteToClient_Single (string line, IConnection client) { try { Log.Out ("NOT IMPLEMENTED: Web.WriteToClient_Single"); } catch (Exception e) { Log.Out ("Error in Web.WriteToClient_Single: " + e); } } } }