Exemplo n.º 1
0
        public override void handleGETRequest(HttpProcessor p)
        {
            try
            {
                string requestedPage = Uri.UnescapeDataString(p.request_url.AbsolutePath.TrimStart('/'));

                string[] requestedPath = p.request_url.Segments;
                string requestedDevice = requestedPath[1].TrimStart('/').TrimEnd('/');
                string requestedMedia = requestedPath[2].TrimStart('/').TrimEnd('/');

                if (requestedMedia == "image.jpg")
                {
                    byte[] latestImage = receiver.GetDevice(requestedDevice).LatestImage;
                    if (latestImage == null)
                        latestImage = new byte[0];
                    p.writeSuccess("image/jpeg", latestImage.Length);
                    p.outputStream.Flush();
                    p.rawOutputStream.Write(latestImage, 0, latestImage.Length);
                }
                else if (requestedMedia.EndsWith("image.mjpg"))
                {
                    p.tcpClient.ReceiveBufferSize = 4;
                    p.tcpClient.SendBufferSize = 4;
                    Console.WriteLine("Beginning mjpg stream");
                    p.writeSuccess("multipart/x-mixed-replace;boundary=hdmiextender");
                    byte[] previousImage = null;
                    byte[] currentImage;
                    while (!this.stopRequested)
                    {
                        try
                        {
                            currentImage = receiver.GetDevice(requestedDevice).LatestImage;
                            if (currentImage == previousImage)
                                Thread.Sleep(1);
                            else
                            {
                                previousImage = currentImage;

                                p.outputStream.WriteLine("--hdmiextender");
                                p.outputStream.WriteLine("Content-Type: image/jpeg");
                                p.outputStream.WriteLine("Content-Length: " + currentImage.Length);
                                p.outputStream.WriteLine();
                                p.outputStream.Flush();
                                p.rawOutputStream.Write(currentImage, 0, currentImage.Length);
                                p.rawOutputStream.Flush();
                                p.outputStream.WriteLine();
                                p.outputStream.Flush();
                            }
                        }
                        catch (Exception ex)
                        {
                            if (!p.isOrdinaryDisconnectException(ex))
                                Logger.Debug(ex);
                            break;
                        }
                    }

                    Console.WriteLine("Ending mjpg stream");
                }
                else if (requestedMedia == "audio.wav")
                {
                    Console.WriteLine("Beginning audio stream");
                    int? audioRegistrationId = null;
                    try
                    {
                        ConcurrentQueue<byte[]> audioData = new ConcurrentQueue<byte[]>();
                        audioRegistrationId = receiver.GetDevice(requestedDevice).RegisterAudioListener(audioData);

                        p.writeSuccess("audio/x-wav");
                        p.outputStream.Flush();
                        byte[] buffer;
                        while (!this.stopRequested)
                        {
                            while (audioData.TryDequeue(out buffer))
                            {
                                p.rawOutputStream.Write(buffer, 0, buffer.Length);
                            }
                            Thread.Sleep(1);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (!p.isOrdinaryDisconnectException(ex))
                            Logger.Debug(ex);
                    }
                    finally
                    {
                        Console.WriteLine("Ending audio stream");
                        if(audioRegistrationId != null)
                            receiver.GetDevice(requestedDevice).UnregisterAudioListener(audioRegistrationId.Value);
                    }
                }
                else if (requestedPage == "raw.html")
                {
                    p.writeSuccess();
                    p.outputStream.Write(@"<html>
            <head>
            <title>Raw MJPEG view</title>
            <style>
            body
            {
            background-color: Black;
            }
            </style>
            </head>
            <body>
            <img src=""image.mjpg"" />
            </body>
            </html>");
                }
            }
            catch (Exception ex)
            {
                if (!p.isOrdinaryDisconnectException(ex))
                    Logger.Debug(ex);
            }
        }
Exemplo n.º 2
0
        public override void handlePOSTRequest(HttpProcessor p, StreamReader inputData)
        {
            Console.WriteLine("POST request: {0}", p.http_url);
            mainLogSingleton.Instance.addResponse(new object[] { "POST request", " : ", p.http_url });

            string data = inputData.ReadToEnd();
            String data2 = HttpUtility.UrlDecode(data);

            p.writeSuccess();
            p.outputStream.WriteLine("<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>");
            p.outputStream.WriteLine("<html><head><meta http-equiv=Content-Type content=text/html; charset=euc-kr /></head><body><h1>test server</h1>");
            p.outputStream.WriteLine("<a href=/test>return</a><p>");
            p.outputStream.WriteLine("postbody: <pre>{0}</pre>", data2);

            Console.WriteLine(data2);
            mainLogSingleton.Instance.addResponse(new object[] { "POST data", " : ", data2 });
        }
Exemplo n.º 3
0
        public override void handlePOSTRequest(HttpProcessor p, StreamReader inputData)
        {
            try
            {
                string requestedPage = p.request_url.AbsolutePath.TrimStart('/');

            }
            catch (Exception ex)
            {
                Logger.Debug(ex);
            }
        }
Exemplo n.º 4
0
        public override void handleGETRequest(HttpProcessor p)
        {
            if (p.http_url.Equals("/Test.png"))
            {
                Stream fs = File.Open("../../Test.png", FileMode.Open);

                p.writeSuccess("image/png");

                //fs.CopyTo (p.outputStream.BaseStream);

                p.outputStream.BaseStream.Flush();
            }

            Console.WriteLine("request: {0}", p.http_url);
            mainLogSingleton.Instance.addResponse(new object[] { "request", p.http_url });
            p.writeSuccess();
            p.outputStream.WriteLine("<html><head><meta http-equiv=Content-Type content=text/html; charset=utf-8 /></head><body><h1>test server</h1>");
            p.outputStream.WriteLine("Current Time: " + DateTime.Now.ToString());
            System.Web.HttpUtility.UrlEncode(p.http_url);
            p.outputStream.WriteLine("url : {0}", p.http_url);

            p.outputStream.WriteLine("<form method=post action=/for11m>");
            p.outputStream.WriteLine("<input type=text name=foo value=foovalue>");
            p.outputStream.WriteLine("<input type=submit name=bar value=barvalue>");

            //System.Web.HttpUtility.UrlEncode
            p.outputStream.WriteLine("</form>");
        }
Exemplo n.º 5
0
 public void listenStart()
 {
     listener = new TcpListener(port);
     //listener.
     listener.Start();
     while (is_active)
     {
         TcpClient s = listener.AcceptTcpClient();
         HttpProcessor processor = new HttpProcessor(s, this);
         Thread thread = new Thread(new ThreadStart(processor.process));
         thread.Start();
         Thread.Sleep(1);
     }
 }
Exemplo n.º 6
0
 public abstract void handlePOSTRequest(HttpProcessor p, StreamReader inputData);
Exemplo n.º 7
0
 public abstract void handleGETRequest(HttpProcessor p);
Exemplo n.º 8
0
        /// <summary>
        /// Listens for connections, somewhat robustly.  Does not return until the server is stopped or until more than 100 listener restarts occur in a single day.
        /// </summary>
        private void listen(object param)
        {
            bool isSecureListener = (bool)param;

            int errorCount = 0;
            DateTime lastError = DateTime.Now;

            TcpListener listener = null;

            while (!stopRequested)
            {
                bool threwExceptionOuter = false;
                try
                {
                    listener = new TcpListener(IPAddress.Any, isSecureListener ? secure_port : port);
                    if (isSecureListener)
                        secureListener = listener;
                    else
                        unsecureListener = listener;
                    listener.Start();
                    while (!stopRequested)
                    {
                        int innerErrorCount = 0;
                        DateTime innerLastError = DateTime.Now;
                        try
                        {
                            TcpClient s = listener.AcceptTcpClient();
                            int workerThreads, completionPortThreads;
                            ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads);
                            // Here is where we could enforce a minimum number of free pool threads,
                            // if we wanted to ensure better performance.
                            if (workerThreads > 0)
                            {
                                HttpProcessor processor = new HttpProcessor(s, this, isSecureListener ? ssl_certificate : null);
                                ThreadPool.QueueUserWorkItem(processor.process);
                            }
                            else
                            {
                                try
                                {
                                    StreamWriter outputStream = new StreamWriter(s.GetStream());
                                    outputStream.WriteLine("HTTP/1.1 503 Service Unavailable");
                                    outputStream.WriteLine("Connection: close");
                                    outputStream.WriteLine("");
                                    outputStream.WriteLine("Server too busy");
                                }
                                catch (ThreadAbortException ex)
                                {
                                    throw ex;
                                }
                            }
                        }
                        catch (ThreadAbortException ex)
                        {
                            throw ex;
                        }
                        catch (Exception ex)
                        {
                            if (DateTime.Now.Hour != innerLastError.Hour || DateTime.Now.DayOfYear != innerLastError.DayOfYear)
                            {
                                innerLastError = DateTime.Now;
                                innerErrorCount = 0;
                            }
                            if (++innerErrorCount > 10)
                                throw ex;
                            SimpleHttpLogger.Log(ex, "Inner Error count this hour: " + innerErrorCount);
                            Thread.Sleep(1);
                        }
                    }
                }
                catch (ThreadAbortException) { stopRequested = true; }
                catch (Exception ex)
                {
                    if (DateTime.Now.DayOfYear != lastError.DayOfYear || DateTime.Now.Year != lastError.Year)
                    {
                        lastError = DateTime.Now;
                        errorCount = 0;
                    }
                    if (++errorCount > 100)
                        throw ex;
                    SimpleHttpLogger.Log(ex, "Restarting listener. Error count today: " + errorCount);
                    threwExceptionOuter = true;
                }
                finally
                {
                    try
                    {
                        if (listener != null)
                        {
                            listener.Stop();
                            if (threwExceptionOuter)
                                Thread.Sleep(1000);
                        }
                    }
                    catch (ThreadAbortException) { stopRequested = true; }
                    catch (Exception) { }
                }
            }
        }