Example #1
0
        public virtual string Start()
        {
            string ret = null;

            LOG.Debug("Starting HTTP server listening on port {0}...", Port);
            try
            {
                Listener.Start();

                int  timeoutSeconds = 3;
                bool isListening    = CheckIsListening(timeoutSeconds);

                if (!isListening)
                {
                    LOG.Error("Failed to start HTTP server listening on port {0}.", Port);
                    return("Failed to start HTTP server");
                }

                LOG.Debug("Calling Listener.BeginGetContext from main thread...");
                RequestProcessorParameter arguments =
                    new RequestProcessorParameter(this.Listener, this.RequestHandler);
                Listener.BeginGetContext(ProcessHttpRequest, arguments);
                LOG.Debug("Continuing main thread after Listener.BeginGetContext...");

                LOG.Debug("HTTP server listening on port {0} has started.", Port);

                return("OK");
            }
            catch (Exception e)
            {
                LOG.Error(e, "Failed to start HTTP server listening on port {0}.", Port);
                return("Failed to start HTTP server: " + e.Message);
            }
        }
        public void Start()
        {
            Listener.Start();
            Listener.BeginGetContext(OnConnection, null !);

            DB.ConnectionAsync().GetAwaiter().GetResult();
        }
 public void Start()
 {
     Logger.Debug("starting HttpListener");
     StopNow = false;
     Listener.Start();
     Listener.BeginGetContext(ListenerCallback, Listener);
 }
Example #4
0
        // Listens for new requests and enqueues them
        private void Listen()
        {
            while (Listener.IsListening)
            {
                // Accept new connection context
                var Context = Listener.BeginGetContext((IAsyncResult Result) =>
                {
                    try
                    {
                        // Lock our context queue to prevent race conditions
                        lock (ContextQueue)
                        {
                            // Add new connection context to our context queue
                            ContextQueue.Enqueue(Listener.EndGetContext(Result));

                            // Signal that a context is ready to be accepted
                            ReadyEvent.Set();
                        }
                    }
                    catch { }
                }, null);

                // Wait for exit
                if (WaitHandle.WaitAny(new[] { StopEvent, Context.AsyncWaitHandle }) == 0)
                {
                    return;
                }
            }
        }
Example #5
0
        // This task is ran Asynchronously each time a request is made
        public void OnContextRequest(IAsyncResult result)
        {
            try
            {
                //The GetContext method blocks while waiting for a request.
                //We use EndGetContext and BeginGetContext instead.
                //As soon as we are done with the last context, we should be listening for the next.
                //That way we can reply to many at the same time.
                Context = Listener.EndGetContext(result);
                Listener.BeginGetContext(OnContextRequest, Listener);

                //Get the specifics of the request and extract the target file/directory.
                string target = context.Request.RawUrl;

                string path = TargetDecoder(target);

                DetermineResponse(path);
            }
            catch (HttpListenerException e)
            {
                // If a connection is terminated mid-download, this will cause an exception.
                // We generally want to avoid that, as this is not fatal.
                Logger.Log(e.Message);
                Logger.Log("Data Stream Terminated early!");
            }
            catch (Exception)
            {
                // Othervise douse everything in gasoline and light a match.
                Logger.Log("Listener Stopped, Stopping Thread");
                throw;
            }
        }
Example #6
0
        // Loop here to begin processing of new requests.
        private void Listen(object state)
        {
            while (Listener.IsListening)
            {
                if (Listener == null)
                {
                    return;
                }

                try
                {
                    Listener.BeginGetContext(ListenerCallback, Listener);
                    _listenForNextRequest.WaitOne();
                }
                catch (Exception ex)
                {
                    _log.Error("Error occurred while host is listening", ex,
                               new Dictionary <string, string>()
                    {
                        { "ErrorCode", "FXD300051" }
                    });
                    return;
                }
                if (Listener == null)
                {
                    return;
                }
            }
        }
Example #7
0
        // Loop here to begin processing of new requests.
        private void Listen(object state, int index)
        {
            while (IsListening)
            {
                if (Listener == null)
                {
                    return;
                }

                try
                {
                    Listener.BeginGetContext(c => ListenerCallback(c, index), Listener);

                    _autoResetEvents[index].WaitOne();
                }
                catch (Exception ex)
                {
                    _logger.Error("Listen()", ex);
                    return;
                }
                if (Listener == null)
                {
                    return;
                }
            }
        }
Example #8
0
        // Loop here to begin processing of new requests.
        private void Listen(object state)
        {
            while (IsListening)
            {
                if (Listener == null)
                {
                    return;
                }

                try
                {
                    Listener.BeginGetContext(ListenerCallback, Listener);
                    listenForNextRequest.WaitOne();
                }
                catch (Exception ex)
                {
                    log.Error("Listen()", ex);
                    return;
                }
                if (Listener == null)
                {
                    return;
                }
            }
        }
Example #9
0
        private void ListenerImplementation()
        {
            var res = Listener.BeginGetContext(new AsyncCallback(ListenerCallback), Listener);

            if (!res.AsyncWaitHandle.WaitOne(1000))
            {
                res.AsyncWaitHandle.Close();
            }
        }
Example #10
0
        private void GetServerCallback <TContext>(IAsyncResult ar) where TContext : Context
        {
            var application = ar.AsyncState as IHttpApplication <TContext>;
            HttpListenerContext httpListenerContext = Listener.EndGetContext(ar);

            //if (httpListenerContext.Request.IsWebSocketRequest)
            //{
            //    var socket = httpListenerContext.AcceptWebSocketAsync("gutsmvc").GetAwaiter().GetResult().WebSocket;
            //    while (true)
            //    {
            //        ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);
            //        WebSocketReceiveResult result = socket.ReceiveAsync(buffer, CancellationToken.None).GetAwaiter().GetResult();
            //        if (socket.State == WebSocketState.Open)
            //        {
            //            string message = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);
            //            string returnMessage = "You send :" + message + ". at" + DateTime.Now.ToLongTimeString();
            //            buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(returnMessage));
            //            socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None).GetAwaiter().GetResult();
            //        }
            //        else
            //        {
            //            break;
            //        }
            //    }

            //}

            Listener.BeginGetContext(GetServerCallback <TContext>, application);

            var t = Task.Factory.StartNew(() =>
            {
                IHttpListenerContextFeature feature = new HttpListenerContextFeature(httpListenerContext, Listener);
                IFeatureCollection contextFeatures  = new FeatureCollection(Services)
                                                      .Set <IHttpRequestFeature>(feature.RequestFeature)
                                                      .Set <IHttpResponseFeature>(feature.ResponseFeature)
                                                      .Set <IWebSocketFeature>(feature.WebSocketFeature);

                TContext context = application.CreateContext(contextFeatures);

                //await application.ProcessRequestAsync(context).ConfigureAwait(false).GetAwaiter().GetResult();
                //application.ProcessRequestAsync(context).ConfigureAwait(false).GetAwaiter()
                //.OnCompleted(() => context.Dispose());
                application.ProcessRequestAsync(context).ConfigureAwait(false).GetAwaiter().GetResult();
                context.Dispose();
                //return context;
            });

            //(t.ConfigureAwait(false).GetAwaiter().GetResult()).Dispose();
        }
Example #11
0
        public void StartListening()
        {
            if (!Listener.IsListening)
            {
                try
                {
                    Listener.Start();
                    OnListenerStart();

                    Listener.BeginGetContext(new AsyncCallback(GetContextCallback), Listener);
                }
                catch (HttpListenerException ex)
                {
                    Logger.Get <WPDListener>().LogTrace(ex.ToString());
                }
            }
        }
        private void OnConnection(IAsyncResult ar)
        {
            try {
                Listener.BeginGetContext(OnConnection, null !);
                var context = Listener.EndGetContext(ar);

                context.Response.ContentEncoding = Encoding.UTF8;
                context.Response.AddHeader("Server", "QuizHub/1.0");
                context.Response.AddHeader("Access-Control-Allow-Origin", "*");

                try {
                    switch (context.Request.HttpMethod)
                    {
                    case "GET":
                        OnGET(context);
                        break;

                    case "POST":
                        OnPOST(context);
                        break;

                    case "OPTIONS":
                        context.Response.Close();
                        break;

                    default:
                        context.Response.Abort();
                        break;
                    }
                } catch (JsonableException ex) {
                    Answer.Json(context, Json.Error(ex));
                } catch (ArgumentException ex) {
                    Answer.Json(context,
                                ex.StackTrace?.Contains("Json.JavaScriptReader") ?? false
                            ? Json.Error(new Ex04_WrongJson())
                            : Json.Error(new Ex01_Unexpected(ex)));
                } catch (Exception ex) {
                    Answer.Json(context, Json.Error(new Ex01_Unexpected(ex)));
                }
            } catch (Exception ex) { Console.WriteLine("ERR: {0}\n\n{1}", ex.Message, ex.StackTrace); }
        }
        private void ListenerCallback(IAsyncResult result)
        {
            // fetch the context
            var context = Listener.EndGetContext(result);

            // get ready for the next request
            Listener.BeginGetContext(ListenerCallback, Listener);

            try
            {
                HandleRequest(context);
            }
            catch (Exception exc)
            {
                Logger.Error("exception thrown while handling HTTP connection", exc);
            }
            finally
            {
                context.Response.Close();
            }
        }
Example #14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="result"></param>
        void GetContextCallback(IAsyncResult result)
        {
            lock (locker)
            {
                if (Listener == null || Listener.IsListening == false)
                {
                    return;
                }

                HttpListenerContext context = Listener.EndGetContext(result);
                logrequest(context);

                try
                {
                    if (IsAuthenticated(context))
                    {
                        string url = context.Request.Url.LocalPath;
                        if (Enable)
                        {
                            if (url == "/")
                            {
                                context.Response.Redirect(Config?.DefaultUrl);
                            }
                            else
                            {
                                wasRestCallBack cb = FindRest(url);
                                if (cb != null)
                                {
                                    StringBuilder sb = new System.Text.StringBuilder();
                                    cb(context, sb);
                                    context.Response.ContentType = FileContentType(".json");
                                    Render(Encode(sb.ToString()), context.Response);
                                }
                                else
                                {
                                    url = Config?.DefaultDir + url;
                                    if (url.Length > 1 && File.Exists(url.Substring(1)))
                                    {
                                        /** Es un fichero lo envio... */
                                        string file = url.Substring(1);
                                        string ext  = Path.GetExtension(file).ToLowerInvariant();

                                        context.Response.ContentType = FileContentType(ext);
                                        ProcessFile(context.Response, file);
                                    }
                                    else
                                    {
                                        context.Response.StatusCode = 404;
                                    }
                                }
                            }
                        }
                        else
                        {
                            // Render(Encode(DisableCause), context.Response);
                            // context.Response.StatusCode = 503;
                            // context.Response.Redirect("/noserver.html");
                            context.Response.ContentType = FileContentType(".html");
                            ProcessFile(context.Response, (Config?.DefaultDir + "/disabled.html").Substring(1), "{{cause}}", DisableCause);
                        }
                    }
                }
                catch (Exception x)
                {
                    Logger.Exception <WebServerBase>(x);
                    context.Response.StatusCode = 500;
                    // Todo. Render(Encode(x.Message), context.Response);
                }
                finally
                {
                    context.Response.Close();
                    if (Listener != null && Listener.IsListening)
                    {
                        Listener.BeginGetContext(new AsyncCallback(GetContextCallback), null);
                    }
                }
            }
        }
Example #15
0
 public void Start()
 {
     Listener.Start();
     Listener.BeginGetContext(OnRequest, Listener);
 }
Example #16
0
        private void ProcessRequest()
        {
            var result = Listener.BeginGetContext(HandleRequest, Listener);

            result.AsyncWaitHandle.WaitOne();
        }
Example #17
0
        public void Start()
        {
            Listener.Start();

            Listener.BeginGetContext(new AsyncCallback(GetContextCallback), Listener);
        }
Example #18
0
        private void BeginWait()
        {
            var state = new object();

            Listener.BeginGetContext(OnContextReceived, state);
        }
Example #19
0
 public void Start()
 {
     // Start listener and accept Http contexts.
     Listener.Start();
     Listener.BeginGetContext(new AsyncCallback(HandleGetContext), this);
 }