示例#1
0
        public static IEnumerable <ThreadInfo> HandleClients(ThreadManager TM)
        {
            var currentThread = TM.CurrentThread;

            while (true)
            {
                int          tries    = 1;
                HttpListener listener = null;
                while (true)
                {
                    try
                    {
                        listener = new HttpListener();
                        listener.Prefixes.Add("http://+:5600/");
                        Console.WriteLine("[{0}]\nAttempt #{1} to start HttpListener...", DateTime.Now, tries);
                        listener.Start();
                        Console.WriteLine("HttpListener successfully started.\n");
                        break;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("HttpListener failed to start with exception:\nMessage: {0}\nStack trace:\n{1}\n", ex.Message, ex.StackTrace);
                        tries++;
                    }
                    if (tries > 5)
                    {
                        Console.WriteLine("[{0}]\nMaximum number of attempts reached.  Try again later.\n", DateTime.Now);
                        yield return(TM.Return(currentThread));
                    }
                    else
                    {
                        Console.WriteLine("[{0}]\nWaiting 5 seconds before attemping again...", DateTime.Now);
                        yield return(TM.Sleep(currentThread, 5000));
                    }
                }
                Console.WriteLine("[{0}]\nWaiting for requests...\n", DateTime.Now);
                while (true)
                {
                    yield return(TM.WaitForClient(currentThread, listener));

                    HttpListenerContext context = null;
                    try
                    {
                        context = TM.GetResult <HttpListenerContext>(currentThread);
                        if (context.Request.RawUrl.StartsWith("/admin/authenticate/"))
                        {
                            Console.WriteLine("[{0}]\nHandling request: {1}\n", DateTime.Now, "/admin/authenticate/...");
                        }
                        else
                        {
                            Console.WriteLine("[{0}]\nHandling request: {1}\n", DateTime.Now, context.Request.RawUrl);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("HttpListener threw an exception while waiting for a client:\nMessage: {0}\nStack trace:\n{1}\n\nGoing to restart the HttpListener...", ex.Message, ex.StackTrace);
                        break;
                    }
                    TM.Enqueue(HandleRequest(TM, context));
                }
                listener.Close();
            }
        }