Exemplo n.º 1
0
 public void Listen()
 {
     try
     {
         using (System.Net.HttpListener listener = new System.Net.HttpListener())
         {
             listener.Prefixes.Add($"http://127.0.0.1:{Port}/");
             listener.Start();
             while (true)
             {
                 var context = listener.GetContext();
                 using (var inputStream = context.Request.InputStream)
                     using (StreamReader sr = new StreamReader(inputStream))
                     {
                         var message = sr.ReadToEnd();
                         Console.WriteLine(message);
                         ProcessPost(message);
                     }
             }
         }
     }
     catch (Exception e)
     {
         Logger.LogException(e);
         throw;
     }
 }
Exemplo n.º 2
0
        public static System.Net.HttpListener StartScriptLogicAsRest(string serviceParameter, Func <object> func)
        {
            var listener = new System.Net.HttpListener();

            listener.Prefixes.Add(string.Format("http://localhost:4567/{0}/", System.Diagnostics.Process.GetCurrentProcess().ProcessName));
            listener.Start();

            while (true)
            {
                System.Net.HttpListenerContext  context  = listener.GetContext();
                System.Net.HttpListenerRequest  request  = context.Request;
                System.Net.HttpListenerResponse response = context.Response;

                string responseString = func().ToString();
                byte[] buffer         = System.Text.Encoding.UTF8.GetBytes(responseString);

                // Get a response stream and write the response to it.
                response.ContentLength64 = buffer.Length;
                System.IO.Stream output = response.OutputStream;
                output.Write(buffer, 0, buffer.Length);

                // You must close the output stream.
                output.Close();
            }
            return(listener);
        }
Exemplo n.º 3
0
        public ServerAsynchronous(string[] prefixes)
        {
            System.Net.HttpListener listener = new System.Net.HttpListener();

            foreach (string prefix in prefixes)
            {
                listener.Prefixes.Add(prefix);
            }

            this.RequestHandler = this.RequestHandlerDefault;

            listener.Start();

            while (this.IsRunning)
            {
                try
                {
                    System.Net.HttpListenerContext context = listener.GetContext();
                    System.Threading.ThreadPool.QueueUserWorkItem
                    (
                        o => RequestHandler(context)
                    );
                }
                catch (Exception exc)
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    sb.Append($"ServerAsynchronous error");

                    throw new InvalidOperationException(sb.ToString(), exc);
                }
            }

            return;
        }
Exemplo n.º 4
0
        private void ListeningAction()
        {
            listener.Start();

            while (true)
            {
                var context = listener.GetContext();
                var method  = context.Request.HttpMethod;
                var url     = context.Request.RawUrl;
                try
                {
                    Logger.OuterLevelWrite("HTTP", () =>
                    {
                        Logger.Log($"Got request: {method} | {context.Request.RawUrl.Replace(Environment.NewLine, "")}");
                        foreach (var controller in responses)
                        {
                            if (controller.RunController(context))
                            {
                                return;
                            }
                        }
                    });
                }
                catch (Exception e)
                {
                    Logger.OuterLevelWrite("HTTP", () => Logger.Log($"Web Error: {e}"));
                }
            }
        }
Exemplo n.º 5
0
 public void Start()
 {
     _listener.AuthenticationSchemes = System.Net.AuthenticationSchemes.Anonymous;
     _listener.Prefixes.Add($"http://{_server}/");
     _listener.Start();
     _running = true;
     _thread  = new System.Threading.Thread(Handle);
     _thread.Start();
 }
Exemplo n.º 6
0
 /// <summary>
 /// Start listener object and set isListening state true
 /// </summary>
 public void Start()
 {
     _listener.Prefixes.Clear();
     foreach (var prefix in _prefixes)
     {
         _listener.Prefixes.Add(prefix);
     }
     _listener.Start();
 }
Exemplo n.º 7
0
        public void Start()
        {
            if (_listener.IsListening)
            {
                return;
            }

            _listener.Start();
            _backgroundWorkerService.RunAsync(Listen);
        }
Exemplo n.º 8
0
        public void CreateListener(List <string> prefixes)
        {
            _listener = new System.Net.HttpListener();
            foreach (string s in prefixes)
            {
                _listener.Prefixes.Add(s);
            }
            _listener.Start();

            var result = _listener.BeginGetContext(new AsyncCallback(ListenerCallback), _listener);
        }
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            http.Prefixes.Add("http://*:80/");
            http.Start();
            Listen();
            string typedMessage;

            do
            {
                typedMessage = Console.ReadLine();
            } while (typedMessage != "EXIT");
            http.Stop();
        }
        public ServerSynchronous(string[] prefixes)
        {
            System.Net.HttpListener listener = new System.Net.HttpListener();

            foreach (string prefix in prefixes)
            {
                listener.Prefixes.Add(prefix);
            }

            listener.Start();

            while (this.IsRunning)
            {
                try
                {
                    var context = listener.GetContext(); //Block until a connection comes in
                    context.Response.StatusCode  = 200;
                    context.Response.SendChunked = true;

                    int totalTime = 0;

                    while (this.IsRunning)
                    {
                        if (totalTime % 3000 == 0)
                        {
                            var bytes = System.Text.Encoding.UTF8.GetBytes(new string('3', 1000) + "\n");
                            context.Response.OutputStream.Write(bytes, 0, bytes.Length);
                        }

                        if (totalTime % 5000 == 0)
                        {
                            var bytes = System.Text.Encoding.UTF8.GetBytes(new string('5', 1000) + "\n");
                            context.Response.OutputStream.Write(bytes, 0, bytes.Length);
                        }

                        System.Threading.Thread.Sleep(1000);
                        totalTime += 1000;
                    }
                }
                catch (Exception exc)
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    sb.Append($"ServerAsync error");

                    throw new InvalidOperationException(sb.ToString(), exc);
                }
            }

            return;
        }
Exemplo n.º 11
0
        public void Start()
        {
            if (listener.IsListening)
            {
                return;
            }

            listener.Start();

            for (int i = 0; i < HandlerThread; i++)
            {
                listener.GetContextAsync().ContinueWith(ProcessRequestHandler);
            }
        }
Exemplo n.º 12
0
 public void WebServerListener()
 {
     try {
         HttpListener.Start();
         while (KeepListening)
         {
             ProcessRequest(HttpListener.GetContext());
         }
         HttpListener.Stop();
     }
     catch (System.Exception E) {
         System.Windows.Forms.MessageBox.Show(E.ToString());
     }
 }
Exemplo n.º 13
0
 private void fluxListener()
 {
     using (var httpListener = new System.Net.HttpListener())
     {
         httpListener.Prefixes.Add("http://localhost:8811/");
         httpListener.Prefixes.Add("http://127.0.0.1:8811/");
         try
         {
             httpListener.Start();
         }
         catch (Exception ex)
         {
             Logger.QueueException("Flux Error", ex);
             return;
         }
         while (!fluxListenerTerminate && Thread.CurrentThread.ThreadState == ThreadState.Background)
         {
             //var ctx = httpListener.GetContext();
             var tsk = httpListener.GetContextAsync();
             if (!tsk.Wait(500))
             {
                 continue;
             }
             var ctx = tsk.Result;
             if (ctx.Request.HttpMethod == "POST")
             {
                 var ct = ctx.Request.QueryString.Get("ct");
                 if (!string.IsNullOrWhiteSpace(ct))
                 {
                     ctx.Response.StatusCode = 200;
                     System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke(
                         () => setColorTemp(colorTemp = int.Parse(ct)));
                     Logger.QueueLine("Color Temp Updated: {0}K", colorTemp);
                 }
                 else
                 {
                     ctx.Response.StatusCode = 404;
                 }
                 using (var strean = ctx.Response.OutputStream)
                 {
                 }
             }
         }
         Logger.QueueLine("Stopping f.lux listener");
         Task.WaitAll(Logger.FlushQueueAsync());
         httpListener.Stop();
     }
 }
Exemplo n.º 14
0
        public void ReadData(string path, string componentName, IDbProcessor dbProcessor)
        {
            System.Net.HttpListener web = null;
            try
            {
                web = new System.Net.HttpListener();
                web.Prefixes.Add(path);
                web.Start();

                do
                {
                    var ctx  = web.GetContext();
                    var req  = ctx.Request;
                    var data = new StreamReader(req.InputStream, req.ContentEncoding).ReadToEnd();

                    if (ProcessorMonitorContainer.ComponentStopper[componentName])
                    {
                        ProcessorMonitorContainer.ComponentStopper[componentName] = false;
                        break;
                    }

                    // parse json into an Entry array
                    var entries = JsonConvert.DeserializeObject <IEntry[]>(data);

                    foreach (var entry in entries)
                    {
                        var lvlType = LevelTypesHelper.GetLevelTypeFromString(entry.Level);

                        IEntry newEntry = EntryFactory.CreateNewEntry
                                          (
                            entry.Timestamp,
                            $"{entry.RenderedMessage}",
                            (int)lvlType,
                            componentName,
                            entry.Exception
                                          );
                        dbProcessor.WriteOne(componentName, newEntry);
                    }
                } while (!ProcessorMonitorContainer.ComponentStopper[componentName]);
            }
            finally
            {
                if (web != null && web.IsListening)
                {
                    web.Stop();
                }
            }
        }
Exemplo n.º 15
0
        private static void IsHttpSysLocked(int port, bool https = false)
        {
            var urlPrefixTemplate = https ? "https://+:{0}/" : "http://+:{0}/";
            var Prefix            = string.Format(urlPrefixTemplate, port);

            var Listener = new System.Net.HttpListener
            {
                IgnoreWriteExceptions = true,
                Prefixes = { Prefix }
            };

            Listener.Start();

            Thread.SpinWait(1);
            Listener.Stop();
        }
Exemplo n.º 16
0
        public void CreateListener(Dictionary <String, X509Certificate2> prefixes)
        {
            var certProc = new CertificateProcessor(ServerComms);

            _listener = new System.Net.HttpListener();


            foreach (string s in prefixes.Keys)
            {
                certProc.AddCertificateToHost(s, prefixes[s]);
                _listener.Prefixes.Add(s);
            }
            _listener.Start();

            var result = _listener.BeginGetContext(new AsyncCallback(ListenerCallback), _listener);
        }
Exemplo n.º 17
0
        private bool TryConnectLocalIP()
        {
            using (var listener = new System.Net.HttpListener())
            {
                listener.Prefixes.Add(ExternalUrl);
                try
                {
                    listener.Start();
                }
                catch (System.Net.HttpListenerException)
                {
                    return(false);
                }
                listener.Close();
            }

            return(true);
        }
Exemplo n.º 18
0
        private bool TryConnectLocalIP()
        {
            using (var listener = new System.Net.HttpListener())
            {
                listener.Prefixes.Add(ExternalUrl);
                try
                {
                    listener.Start();
                }
                catch (System.Net.HttpListenerException e)
                {
                    e.ToString();
                    //System.Console.WriteLine(e);
                    return(false);
                }
                listener.Close();
            }

            return(true);
        }
Exemplo n.º 19
0
        public void Start()
        {
            this.WriteLogMethodName();
            Console.WriteLine("{0}", this.ServerUrlPrimary);
            Console.WriteLine("{0}", this.ServerUrlSecondary);

            HttpListener.Prefixes.Add(this.ServerUrlPrimary);
            HttpListener.Prefixes.Add(this.ServerUrlSecondary);

            // IMPORTANT: If you aren't running this with elevated privileges
            // then the Start() method below will throw an
            // System.Net.HttpListenerException and will have "Access is denied"
            // in its Additional Information

            HttpListener.Start();
            Listen();
            Console.WriteLine("{0} Listening...", typeof(BlogServer).Name);
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
Exemplo n.º 20
0
 //string _http_basehost = "ss.light";
 #region _http_init
 void _http_init(string url)
 {
     _http_listener.Prefixes.Add(url);
     try
     {
         _http_listener.Start();
         _http_beginRecv();
         logger.Log_Warn("Http on:" + url + config.basehost);
     }
     catch (Exception err)
     {
         logger.Log_Error(err.ToString());
         logger.Log_Error("Http Init fail.");
         return;
     }
     if (System.IO.Directory.Exists("publish") == false)
     {
         System.IO.Directory.CreateDirectory("publish");
     }
 }
Exemplo n.º 21
0
        static void Main(string[] args)
        {
            //需要在程序根目录下建立bin目录,把程序拷一份让asp.net加载
            //aspx文件用的codefile模式,不是codebehind模式
            //aspx文件复制到程序运行目录
            var        path = System.Environment.CurrentDirectory;
            SimpleHost msh  = (SimpleHost)System.Web.Hosting.ApplicationHost.CreateApplicationHost(typeof(SimpleHost), "/", path);

            using (var ls = new System.Net.HttpListener())
            {
                ls.Prefixes.Add("http://localhost:8054/");
                ls.Start();
                while (true)
                {
                    var context = ls.GetContext();
                    context.Response.ContentType = "text/html; Charset=UTF-8";
                    context.Response.StatusCode  = 200;
                    System.Threading.ThreadPool.QueueUserWorkItem(x => msh.ProcessRequest(context.Request.Url, context.Response.OutputStream));
                }
            }
        }
Exemplo n.º 22
0
        public void CreateListener(Dictionary <String, X509Certificate2> prefixes)
        {
            var certProc = new CertificateProcessor(ServerComms);

            _listener = new System.Net.HttpListener();


            foreach (string s in prefixes.Keys)
            {
                certProc.AddCertificateToHost(s, prefixes[s]);
                _listener.Prefixes.Add(s);
            }
            _listener.Start();

            System.Threading.Tasks.Task.Factory.StartNew(() => {
                while (_listener.IsListening)
                {
                    var result = _listener.BeginGetContext(new AsyncCallback(ListenerCallback), _listener);
                    result.AsyncWaitHandle.WaitOne();
                }
            });
        }
Exemplo n.º 23
0
        void Web()
        {
            System.Net.HttpListener listener = new System.Net.HttpListener();
            //Properties.Settings.Default.Host
            //listener.Prefixes.Add("http://localhost:8888/");
            listener.Prefixes.Add(Properties.Settings.Default.Host);
            listener.Start();
            System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    try
                    {
                        System.Net.HttpListenerContext context = listener.GetContext();
                        System.Net.HttpListenerRequest request = context.Request;
                        //DataStart = 2005-08-09T18: 31:42 & DataEnd = 2005-08-09T18: 31:42

                        var str = request.RawUrl.Split('&');
                        switch (str[0].ToUpper())
                        {
                        case "/WEIGHING":
                            WebWeighing(str, context);
                            break;

                        case "/CARS":
                            WebCars(str, request, context);
                            break;

                        case "/SHIPPERS":
                            WebShippers(str, request, context);
                            break;

                        case "/CONSIGNEE":
                            WebConsignee(str, request, context);
                            break;

                        case "/WEIGHMAN":
                            WebWeighman(str, request, context);
                            break;

                        case "/WEIGHINGMODE":
                            WebWeighingMode(str, context);
                            break;

                        case "/MATERIAL":
                            WebMaterial(str, request, context);
                            break;
                        }

                        /*
                         * MemoryStream stream1 = new MemoryStream();
                         * DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(RecordWeight[]), new DataContractJsonSerializerSettings
                         * {
                         * DateTimeFormat = new DateTimeFormat("yyyy-MM-dd'T'HH:mm:ss")
                         * });
                         * DateTime Start = DateTime.MinValue;
                         * DateTime End = DateTime.MaxValue;
                         * if (str[1].StartsWith("DateStart="))
                         * {
                         * var ts = str[1].Substring(10);
                         * Start = DateTime.Parse(ts);
                         * }
                         *
                         * if (str[2].StartsWith("DateEnd="))
                         * {
                         * var ts = str[2].Substring(8);
                         * End = DateTime.Parse(ts);
                         * }
                         * var rdr = new StreamReader(stream1, Encoding.UTF8);
                         * if (Start > End)
                         * continue;
                         * RecordWeight[] rec;
                         * lock (listWeight)
                         * {
                         * rec = listWeight.ToArray();
                         * }
                         * rec = rec.Where(x =>
                         * {
                         * var date = x.dataBrutto > x.dataTara ? x.dataBrutto : x.dataTara;
                         * return date >= Start && date <= End;
                         * }).ToArray();
                         * ser.WriteObject(stream1, rec);
                         * stream1.Position = 0;
                         * var ret = rdr.ReadToEnd();
                         * rdr.Close();
                         * stream1.Close();
                         * {
                         * {
                         *  System.Net.HttpListenerResponse response = context.Response;
                         *  response.ContentType = "application/json";
                         *
                         *  string responseString = ret;
                         *
                         *  byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
                         *  response.ContentLength64 = buffer.Length;
                         *  Stream output = response.OutputStream;
                         *  output.Write(buffer, 0, buffer.Length);
                         *  output.Close();
                         * }
                         * }*/
                    } catch { }
                }
            });
        }
Exemplo n.º 24
0
        public void Run()
        {
            if (!IsConnectedToInternet())
            {
                System.Console.WriteLine("Not connected to a network");
                return;
            }

            bool useLocalIP = true;
            if (!TryConnectLocalIP())
            {
                useLocalIP = false;
                System.Console.WriteLine("Could not connect through local IP address");
            }

            System.Console.WriteLine("Connect using {0}", baseUrl.TrimEnd('/'));
            if (useLocalIP)
            {
                System.Console.WriteLine("Connect using {0}", ExternalUrl.TrimEnd('/'));
            }

            using (var listener = new System.Net.HttpListener())
            {
                listener.Prefixes.Add(baseUrl);
                if (useLocalIP)
                {
                    listener.Prefixes.Add(ExternalUrl);
                }

                listener.Start();
                while (true)
                {
                    System.Net.HttpListenerContext ctx = listener.GetContext();
                    System.Net.HttpListenerRequest request = ctx.Request;
                    System.Console.WriteLine(request.Url);

                    System.Net.HttpListenerResponse response = ctx.Response;

                    string urlString = request.Url.ToString();
                    string rawUrl = request.RawUrl.ToString();

                    string responseText = null;

                    byte[] reponseBuffer = null;
                    if (rawUrl == root)
                    {
                        responseText = defaultPage;
                        responseText = responseText.Replace(baseUrl, urlString + "/");
                        response.ContentType = "text/HTML";
                    }
                    else if (rawUrl.StartsWith(WebService.resourcePrefix))
                    {
                        string resourceName = rawUrl.Remove(0, WebService.resourcePrefix.Length);
                        if (rawUrl.EndsWith(".jpg"))
                        {
                            reponseBuffer = Program.GetEmbeddedContentAsBinary(resourceName);
                            response.ContentType = System.Net.Mime.MediaTypeNames.Image.Jpeg;
                        }
                        else
                        {
                            responseText = Program.GetEmbeddedContent(resourceName);
                            response.ContentType = "text/css";
                        }
                    }
                    else if (rawUrl.StartsWith(root + "/"))
                    {
                        var streamReader = new System.IO.StreamReader(request.InputStream, request.ContentEncoding);
                        var jsonRequest = streamReader.ReadToEnd();

                        string requestedPage = rawUrl.Remove(0, (root + "/").Length);
                        object unserializedObject = null;

                        Type serviceType;
                        if (mapNameToServiceType.TryGetValue(requestedPage, out serviceType))
                        {
                            unserializedObject = js.Deserialize(jsonRequest, serviceType);
                            if (unserializedObject == null)
                            {
                                unserializedObject = Activator.CreateInstance(serviceType);
                            }
                        }
                        else
                        {
                            System.Console.WriteLine("Unrecognized Service");
                        }

                        if (unserializedObject is IRequestWithHtmlResponse)
                        {
                            responseText = ((IRequestWithHtmlResponse)unserializedObject).GetResponse(this);
                        }
                        else if (unserializedObject is IRequestWithJsonResponse)
                        {
                            object o = ((IRequestWithJsonResponse)unserializedObject).GetResponse(this);
                            var serialized = js.Serialize(o);
                            responseText = serialized;
                        }
                        response.ContentType = "text/html";
                    }

                    if (response.ContentType != null && response.ContentType.StartsWith("text") && responseText != null)
                    {
                        response.ContentEncoding = System.Text.UTF8Encoding.UTF8;
                        reponseBuffer = System.Text.Encoding.UTF8.GetBytes(responseText);
                    }

                    if (reponseBuffer != null)
                    {
                        //These headers to allow all browsers to get the response
                        response.Headers.Add("Access-Control-Allow-Credentials", "true");
                        response.Headers.Add("Access-Control-Allow-Origin", "*");
                        response.Headers.Add("Access-Control-Origin", "*");

                        //response.StatusCode = 200;
                        //response.StatusDescription = "OK";
                        // Get a response stream and write the response to it.
                        response.ContentLength64 = reponseBuffer.Length;
                        System.IO.Stream output = response.OutputStream;
                        output.Write(reponseBuffer, 0, reponseBuffer.Length);
                        output.Close();
                    }
                    response.Close();
                }
            }
        }
Exemplo n.º 25
0
        private bool TryConnectLocalIP()
        {
            using (var listener = new System.Net.HttpListener())
            {
                listener.Prefixes.Add(ExternalUrl);
                try
                {
                    listener.Start();
                }
                catch(System.Net.HttpListenerException e)
                {
                    e.ToString();
                    //System.Console.WriteLine(e);
                    return false;
                }
                listener.Close();
            }

            return true;
        }
Exemplo n.º 26
0
        static void Main(string[] args)
        {
            try
            {
                System.Net.HttpListener server = new System.Net.HttpListener();
                // Address, Port を指定
                server.Prefixes.Add("http://localhost:8000/");
                // サーバ起動
                server.Start();

                while (true)
                {
                    // 接続待ち
                    System.Net.HttpListenerContext context = server.GetContext();

                    // 応答作成
                    System.Net.HttpListenerResponse response = context.Response;
                    // JavaScriptエラー回避
                    response.Headers.Add("Access-Control-Allow-Origin", "*");

                    bool   readSuccess = false;
                    byte[] idm         = null;

                    if (System.Text.RegularExpressions.Regex.IsMatch(context.Request.Url.ToString(), "http://localhost:8000/getIDmDummy\\?seed=.*"))
                    {
                        // 疑似IDm生成
                        idm         = IDmDummy(context.Request.QueryString.Get("seed"));
                        readSuccess = true;

                        Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}]\t疑似IDm生成");
                    }
                    else
                    {
                        try
                        {
                            // NFC読み込み
                            Felica felica = new Felica();
                            felica.Polling((int)SystemCode.FelicaLiteS);
                            idm = felica.IDm();
                            felica.Dispose();

                            readSuccess = true;

                            Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}]\tカード読み取り成功");
                        }
                        catch
                        {
                            Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}]\tカード読み取り失敗");
                        }
                    }

                    if (readSuccess)
                    {
                        // 読み取り成功
                        string idm_str = BitConverter.ToString(idm).Replace("-", "").ToLower();
                        idm = Encoding.UTF8.GetBytes(idm_str);

                        response.StatusCode = 200;
                        response.OutputStream.Write(idm, 0, idm.Length);
                        response.Close();
                    }
                    else
                    {
                        // 読み取り失敗
                        response.StatusCode = 500;
                        response.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Exemplo n.º 27
0
 public void StartServer(int port)//启动服务器
 {
     host.Prefixes.Add("http://*:" + port + "/");
     host.Start();
     host.BeginGetContext(onHttpIn, null);
 }
Exemplo n.º 28
0
        private void _Server()
        {
            Trace.TraceInformation("Enter.");

            System.Net.HttpListener _Listener = null;
            string sResponse = string.Empty;

            try
            {
                _Listener = new System.Net.HttpListener();
                _Listener.Prefixes.Add("http://" + _WebServerIP + ":" + _WebServerPort + "/" + _WebServerURIPrefix + "/");
                _Listener.Start();

                Trace.TraceInformation("Listener started for prefix " + "http://" + _WebServerIP + ":" + _WebServerPort + "/" + _WebServerURIPrefix + "/");

                if (Started != null)
                {
                    Started(this, new EventArgs());
                }

                do
                {
                    Trace.TraceInformation("Listening for request to be processed asyncronously.");

                    IAsyncResult result = _Listener.BeginGetContext(_Callback, _Listener);

                    Trace.TraceInformation("Waiting for request to be processed asyncronously.");

                    result.AsyncWaitHandle.WaitOne();

                    Trace.TraceInformation("Request processed asyncronously.");
                } while (true);
            }
            catch (System.Threading.ThreadAbortException abortEx)
            {
                Trace.TraceError("ThreadAbortException:" + abortEx.Message + Environment.NewLine + "StackTrace:" + abortEx.StackTrace);

                System.Threading.Thread.ResetAbort();

                _Abort.Set();

                if (Aborted != null)
                {
                    Aborted(this, new EventArgs());
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("Exception:" + ex.Message + Environment.NewLine + "StackTrace:" + ex.StackTrace);

                _Abort.Set();

                if (Error != null)
                {
                    Error(this, new WebServerEventArgs("Exception:" + ex.Message + Environment.NewLine + "StackTrace:" + ex.StackTrace));
                }
            }
            finally
            {
                if (_Listener != null)
                {
                    if (_Listener.IsListening)
                    {
                        _Listener.Stop();
                    }
                }

                _Listener = null;
            }

            if (Stopped != null)
            {
                Stopped(this, new EventArgs());
            }
        }
Exemplo n.º 29
0
        public void Run()
        {
            if (!IsConnectedToInternet())
            {
                System.Console.WriteLine("Not connected to a network");
                return;
            }

            bool useLocalIP = true;

            if (!TryConnectLocalIP())
            {
                useLocalIP = false;
                System.Console.WriteLine("Could not connect through local IP address");
            }

            System.Console.WriteLine("Connect using {0}", baseUrl.TrimEnd('/'));
            if (useLocalIP)
            {
                System.Console.WriteLine("Connect using {0}", ExternalUrl.TrimEnd('/'));
            }

            using (var listener = new System.Net.HttpListener())
            {
                listener.Prefixes.Add(baseUrl);
                if (useLocalIP)
                {
                    listener.Prefixes.Add(ExternalUrl);
                }

                listener.Start();
                while (true)
                {
                    System.Net.HttpListenerContext ctx     = listener.GetContext();
                    System.Net.HttpListenerRequest request = ctx.Request;
                    System.Console.WriteLine(request.Url);

                    System.Net.HttpListenerResponse response = ctx.Response;

                    string urlString = request.Url.ToString();
                    string rawUrl    = request.RawUrl.ToString();

                    string responseText = null;

                    byte[] reponseBuffer = null;
                    if (rawUrl == root)
                    {
                        responseText         = defaultPage;
                        responseText         = responseText.Replace(baseUrl, urlString + "/");
                        response.ContentType = "text/HTML";
                    }
                    else if (rawUrl.StartsWith(WebService.resourcePrefix))
                    {
                        string resourceName = rawUrl.Remove(0, WebService.resourcePrefix.Length);
                        if (rawUrl.EndsWith(".jpg"))
                        {
                            reponseBuffer        = Program.GetEmbeddedContentAsBinary(resourceName);
                            response.ContentType = System.Net.Mime.MediaTypeNames.Image.Jpeg;
                        }
                        else
                        {
                            responseText         = Program.GetEmbeddedContent(resourceName);
                            response.ContentType = "text/css";
                        }
                    }
                    else if (rawUrl.StartsWith(root + "/"))
                    {
                        var streamReader = new System.IO.StreamReader(request.InputStream, request.ContentEncoding);
                        var jsonRequest  = streamReader.ReadToEnd();

                        string requestedPage      = rawUrl.Remove(0, (root + "/").Length);
                        object unserializedObject = null;

                        Type serviceType;
                        if (mapNameToServiceType.TryGetValue(requestedPage, out serviceType))
                        {
                            unserializedObject = js.Deserialize(jsonRequest, serviceType);
                            if (unserializedObject == null)
                            {
                                unserializedObject = Activator.CreateInstance(serviceType);
                            }
                        }
                        else
                        {
                            System.Console.WriteLine("Unrecognized Service");
                        }

                        if (unserializedObject is IRequestWithHtmlResponse)
                        {
                            responseText = ((IRequestWithHtmlResponse)unserializedObject).GetResponse(this);
                        }
                        else if (unserializedObject is IRequestWithJsonResponse)
                        {
                            object o          = ((IRequestWithJsonResponse)unserializedObject).GetResponse(this);
                            var    serialized = js.Serialize(o);
                            responseText = serialized;
                        }
                        response.ContentType = "text/html";
                    }

                    if (response.ContentType != null && response.ContentType.StartsWith("text") && responseText != null)
                    {
                        response.ContentEncoding = System.Text.UTF8Encoding.UTF8;
                        reponseBuffer            = System.Text.Encoding.UTF8.GetBytes(responseText);
                    }

                    if (reponseBuffer != null)
                    {
                        //These headers to allow all browsers to get the response
                        response.Headers.Add("Access-Control-Allow-Credentials", "true");
                        response.Headers.Add("Access-Control-Allow-Origin", "*");
                        response.Headers.Add("Access-Control-Origin", "*");

                        //response.StatusCode = 200;
                        //response.StatusDescription = "OK";
                        // Get a response stream and write the response to it.
                        response.ContentLength64 = reponseBuffer.Length;
                        System.IO.Stream output = response.OutputStream;
                        output.Write(reponseBuffer, 0, reponseBuffer.Length);
                        output.Close();
                    }
                    response.Close();
                }
            }
        }