// Thread entry point
        public void WorkerThread()
        {
            byte[] buffer = new byte[bufSize];                  // buffer to read stream

            while (true)
            {
                // reset reload event
                reloadEvent.Reset();

                HttpWebRequest req = null;
                WebResponse    resp = null;
                Stream         stream = null;
                byte[]         delimiter = null;
                byte[]         delimiter2 = null;
                byte[]         boundary = null;
                int            boundaryLen, delimiterLen = 0, delimiter2Len = 0;
                int            read, todo = 0, total = 0, pos = 0, align = 1;
                int            start = 0, stop = 0;

                // align
                //  1 = searching for image start
                //  2 = searching for image end
                try
                {
                    // create request
                    req = (HttpWebRequest)WebRequest.Create(source);
                    // set login and password
                    if (string.IsNullOrEmpty(login) == false && string.IsNullOrEmpty(password) == false)
                    {
                        Uri sourceUri = new Uri(source);
                        Uri homePage  = new Uri(sourceUri.Scheme + "://" + sourceUri.Authority);

                        CredentialCache c = new CredentialCache();
                        c.Add(homePage, "Basic", new NetworkCredential(login, password));
                        c.Add(sourceUri, "Basic", new NetworkCredential(login, password));
                        if (this.authWithHomePage)
                        {
                            try
                            {
                                WebRequest r = WebRequest.Create(homePage);
                                r.PreAuthenticate = this.PreAuthenticate;
                                r.Credentials     = c;
                                WebResponse  s  = r.GetResponse();
                                StreamReader sr = new StreamReader(s.GetResponseStream());
                                char[]       b  = new char[5000];
                                sr.Read(b, 0, 5000);
                                sr.Close();
                                s.Close();
                            }
                            catch (Exception ex)
                            {
                                System.Diagnostics.Debug.WriteLine("=============: " + ex.Message);
                                throw;
                            }
                        }



                        req.PreAuthenticate = true;
                        req.Credentials     = c;
                    }

                    // set connection group name
                    if (useSeparateConnectionGroup)
                    {
                        req.ConnectionGroupName = GetHashCode().ToString();
                    }
                    // get response
                    resp = req.GetResponse();

                    // check content type
                    string ct = resp.ContentType;
                    if (ct.IndexOf("multipart/x-mixed-replace") == -1)
                    {
                        throw new ApplicationException("Invalid URL");
                    }

                    // get boundary
                    ASCIIEncoding encoding = new ASCIIEncoding();
                    boundary    = encoding.GetBytes(ct.Substring(ct.IndexOf("boundary=", 0) + 9));
                    boundaryLen = boundary.Length;

                    // get response stream
                    stream = resp.GetResponseStream();

                    // loop
                    while ((!stopEvent.WaitOne(0, true)) && (!reloadEvent.WaitOne(0, true)))
                    {
                        // check total read
                        if (total > bufSize - readSize)
                        {
                            System.Diagnostics.Debug.WriteLine("flushing");
                            total = pos = todo = 0;
                        }

                        // read next portion from stream
                        if ((read = stream.Read(buffer, total, readSize)) == 0)
                        {
                            throw new ApplicationException();
                        }

                        total += read;
                        todo  += read;

                        // increment received bytes counter
                        bytesReceived += read;

                        // does we know the delimiter ?
                        if (delimiter == null)
                        {
                            // find boundary
                            pos = ByteArrayUtils.Find(buffer, boundary, pos, todo);

                            if (pos == -1)
                            {
                                // was not found
                                todo = boundaryLen - 1;
                                pos  = total - todo;
                                continue;
                            }

                            todo = total - pos;

                            if (todo < 2)
                            {
                                continue;
                            }

                            // check new line delimiter type
                            if (buffer[pos + boundaryLen] == 10)
                            {
                                delimiterLen = 2;
                                delimiter    = new byte[2] {
                                    10, 10
                                };
                                delimiter2Len = 1;
                                delimiter2    = new byte[1] {
                                    10
                                };
                            }
                            else
                            {
                                delimiterLen = 4;
                                delimiter    = new byte[4] {
                                    13, 10, 13, 10
                                };
                                delimiter2Len = 2;
                                delimiter2    = new byte[2] {
                                    13, 10
                                };
                            }

                            pos += boundaryLen + delimiter2Len;
                            todo = total - pos;
                        }

                        // boundary aligned

                        /*						if ((align == 0) && (todo >= boundaryLen))
                         *                                              {
                         *                                                      if (ByteArrayUtils.Compare(buffer, boundary, pos))
                         *                                                      {
                         *                                                              // boundary located
                         *                                                              align = 1;
                         *                                                              todo -= boundaryLen;
                         *                                                              pos += boundaryLen;
                         *                                                      }
                         *                                                      else
                         *                                                              align = 2;
                         *                                              }*/

                        // search for image
                        if (align == 1)
                        {
                            start = ByteArrayUtils.Find(buffer, delimiter, pos, todo);
                            if (start != -1)
                            {
                                // found delimiter
                                start += delimiterLen;
                                pos    = start;
                                todo   = total - pos;
                                align  = 2;
                            }
                            else
                            {
                                // delimiter not found
                                todo = delimiterLen - 1;
                                pos  = total - todo;
                            }
                        }

                        // search for image end
                        while ((align == 2) && (todo >= boundaryLen))
                        {
                            stop = ByteArrayUtils.Find(buffer, boundary, pos, todo);
                            if (stop != -1)
                            {
                                pos  = stop;
                                todo = total - pos;

                                // increment frames counter
                                framesReceived++;

                                // image at stop
                                if (NewFrame != null)
                                {
                                    Bitmap bmp = (Bitmap)Bitmap.FromStream(new MemoryStream(buffer, start, stop - start));
                                    // notify client
                                    NewFrame(this, new CameraEventArgs(bmp));
                                    // release the image
                                    bmp.Dispose();
                                    bmp = null;
                                }
//								System.Diagnostics.Debug.WriteLine("found image end, size = " + (stop - start));

                                // shift array
                                pos  = stop + boundaryLen;
                                todo = total - pos;
                                Array.Copy(buffer, pos, buffer, 0, todo);

                                total = todo;
                                pos   = 0;
                                align = 1;
                            }
                            else
                            {
                                // delimiter not found
                                todo = boundaryLen - 1;
                                pos  = total - todo;
                            }
                        }
                    }
                }
                catch (WebException ex)
                {
                    System.Diagnostics.Debug.WriteLine("=============: " + ex.Message);
                    // wait for a while before the next try
                    Thread.Sleep(250);
                }
                catch (ApplicationException ex)
                {
                    System.Diagnostics.Debug.WriteLine("=============: " + ex.Message);
                    // wait for a while before the next try
                    Thread.Sleep(250);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("=============: " + ex.Message);
                }
                finally
                {
                    // abort request
                    if (req != null)
                    {
                        req.Abort();
                        req = null;
                    }
                    // close response stream
                    if (stream != null)
                    {
                        stream.Close();
                        stream = null;
                    }
                    // close response
                    if (resp != null)
                    {
                        resp.Close();
                        resp = null;
                    }
                }

                // need to stop ?
                if (stopEvent.WaitOne(0, true))
                {
                    break;
                }
            }
        }
示例#2
0
        // Thread entry point
        public void WorkerThread()
        {
            byte[]        delimiter     = null;
            byte[]        delimiter2    = null;
            byte[]        boundary      = null;
            int           boundaryLen   = 0;
            int           delimiterLen  = 0;
            int           delimiter2Len = 0;
            int           read          = 0;
            int           todo          = 0;
            int           total         = 0;
            int           pos           = 0;
            int           align         = 1;
            int           start         = 0;
            int           stop          = 0;
            ASCIIEncoding encoding;

            byte[]          buffer = null;
            HttpWebRequest  req    = null;
            HttpWebResponse resp   = null;
            // MemoryStream
            Stream stream = null;

            //byte[] mmsb = new byte[50000];//1024000
            byte[]       mmsb = new byte[100];//1024000
            MemoryStream mms  = new MemoryStream(mmsb);
            //Bitmap bmp;
            Image  bmp;
            string ct = "";

            while (yx & mjpeg.TC.yx)
            {
                delimiter     = null;
                delimiter2    = null;
                boundary      = null;
                boundaryLen   = 0;
                delimiterLen  = 0;
                delimiter2Len = 0;
                read          = 0;
                todo          = 0;
                total         = 0;
                pos           = 0;
                align         = 1; // align                //  1 = searching for image start                //  2 = searching for image end
                start         = 0;
                stop          = 0;
                req           = null;
                resp          = null;
                stream        = null;
                GC.Collect();
                if (IsExistC())
                {
                    // get boundary
                    encoding = new ASCIIEncoding();
                    buffer   = new byte[bufSize];       // buffer to read stream
                    ct       = "";
                    mmsb     = new byte[50000];
                    // create request
                    try
                    {
                        req  = null;
                        resp = null;
                        lock (this)
                        {
                            // source = source + "&compression=30&resolution=2CIF&date=0";
                            req                  = (HttpWebRequest)WebRequest.Create(source);
                            req.Timeout          = 50000; // 1000;// 50000; //已重写。获取或设置 GetResponse 和 GetRequestStream 方法的超时值。
                            req.ReadWriteTimeout = 20000; //1000
                            mms                  = new MemoryStream(mmsb);
                            Thread.Sleep(50);
                            //// set login and password
                            //if ((login != null) && (password != null) && (login != ""))
                            req.Credentials = new NetworkCredential("ttsj", "ttsjfc");
                            // get response
                            resp = (HttpWebResponse)req.GetResponse();
                            if (resp.StatusCode != HttpStatusCode.OK)
                            {
                                throw new ApplicationException("服务器响应不正确");
                            }
                            // check content type
                            ct = resp.ContentType;
                            //ct = req.ContentType;
                            if (ct.IndexOf("multipart/x-mixed-replace") == -1)
                            {
                                throw new ApplicationException("Invalid URL");
                            }
                            // get response stream
                            stream = resp.GetResponseStream();
                            if (ct.IndexOf("boundary=", 0) >= 0)
                            {
                                boundary = encoding.GetBytes(ct.Substring(ct.IndexOf("boundary=", 0) + 9));
                            }
                            boundaryLen = boundary.Length;
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.Write(" mjpeg1:" + ex.ToString() + source);
                        err = ex.ToString();
                        if (ErrEvent != null)
                        {
                            ErrEvent(this, err);
                        }

                        if (resp != null)
                        {
                            resp.Close();
                        }
                        if (req != null)
                        {
                            req.Abort();
                        }
                        continue;
                    }
                    int cw0 = 0;
                    #region  //x  while
                    while (yx)
                    {
                        try
                        {
                            // check total read
                            if (total > bufSize - readSize)
                            {
                                total = pos = todo = 0;
                            }
                            Thread.Sleep(waitTime);   //2005-11  //10  2006-4-26
                            read = stream.Read(buffer, total, buffer.Length - total);
                            if (read == 0)
                            {
                                cw0 = cw0 + 1;
                            }
                            if (cw0 > 10)
                            {
                                cw0 = 0;
                                break;
                            }
                            //continue;
                            total += read;
                            todo  += read;

                            // increment received bytes counter
                            bytesReceived += read;
                            // does we know the delimiter ?
                            if (delimiter == null)
                            {
                                // find boundary
                                pos = ByteArrayUtils.Find(buffer, boundary, pos, todo);
                                if (pos == -1)
                                {                                      // was not found
                                    todo = boundaryLen - 1;
                                    pos  = total - todo;
                                    continue;
                                }
                                todo = total - pos;
                                if (todo < 2)
                                {
                                    continue;
                                }
                                // check new line delimiter type
                                if (buffer[pos + boundaryLen] == 10)
                                {
                                    delimiterLen = 2;
                                    delimiter    = new byte[2] {
                                        10, 10
                                    };
                                    delimiter2Len = 1;
                                    delimiter2    = new byte[1] {
                                        10
                                    };
                                }
                                else
                                {
                                    delimiterLen = 4;
                                    delimiter    = new byte[4] {
                                        13, 10, 13, 10
                                    };
                                    delimiter2Len = 2;
                                    delimiter2    = new byte[2] {
                                        13, 10
                                    };
                                }

                                pos += boundaryLen + delimiter2Len;
                                todo = total - pos;
                            }
                            if (align == 1)
                            {
                                start = ByteArrayUtils.Find(buffer, delimiter, pos, todo);
                                if (start != -1)
                                {
                                    // found delimiter
                                    start += delimiterLen;
                                    pos    = start;
                                    todo   = total - pos;
                                    align  = 2;
                                }
                                else
                                {
                                    // delimiter not found
                                    todo = delimiterLen - 1;
                                    pos  = total - todo;
                                }
                            }
                            //  continue;
                            // search for image end
                            while ((align == 2) && (todo >= boundaryLen))
                            {
                                stop = ByteArrayUtils.Find(buffer, boundary, pos, todo);
                                if (stop != -1)
                                {
                                    pos  = stop;
                                    todo = total - pos;
                                    // increment frames counter
                                    framesReceived++;
                                    // continue;
                                    // image at stop
                                    if (NewFrame != null)
                                    {
                                        if (mmsb.Length != stop - start)
                                        {
                                            mmsb = new byte[stop - start];
                                            //Array.Copy(buffer, start, mmsb, 0, stop - start);
                                            Buffer.BlockCopy(buffer, start, mmsb, 0, stop - start);
                                            mms = new MemoryStream(mmsb);
                                        }
                                        else
                                        {
                                            //Array.Copy(buffer, start, mmsb, 0, stop - start);
                                            Buffer.BlockCopy(buffer, start, mmsb, 0, stop - start);
                                        }
                                        bmp = Image.FromStream(mms, false, false);
                                        // notify client
                                        NewFrame(this, bmp);
                                    }
                                    // shift array
                                    pos  = stop + boundaryLen;
                                    todo = total - pos;
                                    //Array.Copy(buffer, pos, buffer, 0, todo);
                                    Buffer.BlockCopy(buffer, pos, buffer, 0, todo);
                                    total = todo;
                                    pos   = 0;
                                    align = 1;
                                }
                                else
                                {
                                    // delimiter not found
                                    todo = boundaryLen - 1;
                                    pos  = total - todo;
                                }
                            }
                        }
                        catch (Exception ex3)
                        {
                            System.Diagnostics.Debug.Write(" mjpeg2::" + ex3.ToString() + source);
                            err = ex3.ToString();
                            if (ErrEvent != null)
                            {
                                ErrEvent(this, err);
                            }
                            if (resp != null)
                            {
                                resp.Close();
                            }
                            if (req != null)
                            {
                                req.Abort();
                            }
                            break;
                        }
                    }
                    #endregion  //xwhile
                }
                else
                {
                    err = "IP地址不通";
                    Thread.Sleep(50);
                }
            } //while
        }     //method