예제 #1
0
        // 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 ((login != null) && (password != null) && (login != ""))
                    {
                        req.Credentials = new NetworkCredential(login, password);
                    }
                    // 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)
                        {
                            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;
                        }

                        // 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;
                                }

                                // 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
        // 线程入口
        public void WorkerThread()
        {
            byte[] buffer = new byte[bufSize];                // buffer 用于读取流

            while (true)
            {
                // 重置reload事件
                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;

                // 排序
                //  1 = 查询图片的开始
                //  2 = 查询图片的结束
                try
                {
                    // 创建请求
                    req = (HttpWebRequest)WebRequest.Create(source);
                    // 设置用户名和密码
                    if ((login != null) && (password != null) && (login != ""))
                    {
                        req.Credentials = new NetworkCredential(login, password);
                    }
                    // 设置连接组名
                    if (useSeparateConnectionGroup)
                    {
                        req.ConnectionGroupName = GetHashCode().ToString();
                    }
                    // 获取响应
                    resp = req.GetResponse();

                    // 检查内容类型
                    string ct = resp.ContentType;
                    if (ct.IndexOf("multipart/x-mixed-replace") == -1)
                    {
                        throw new ApplicationException("Invalid URL");
                    }

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

                    // 获取响应流
                    stream = resp.GetResponseStream();

                    // 循环
                    while ((!stopEvent.WaitOne(0, true)) && (!reloadEvent.WaitOne(0, true)))
                    {
                        if (total > bufSize - readSize)
                        {
                            total = pos = todo = 0;
                        }

                        // 读取流的下一部分
                        if ((read = stream.Read(buffer, total, readSize)) == 0)
                        {
                            throw new ApplicationException();
                        }

                        total += read;
                        todo  += read;

                        // increment received bytes counter
                        bytesReceived += read;

                        if (delimiter == null)
                        {
                            // 找到边界
                            pos = ByteArrayUtils.Find(buffer, boundary, pos, todo);

                            if (pos == -1)
                            {
                                // 没有找到
                                todo = boundaryLen - 1;
                                pos  = total - todo;
                                continue;
                            }

                            todo = total - pos;

                            if (todo < 2)
                            {
                                continue;
                            }

                            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)
                            {
                                // 找到delimiter
                                start += delimiterLen;
                                pos    = start;
                                todo   = total - pos;
                                align  = 2;
                            }
                            else
                            {
                                // delimiter没有找到
                                todo = delimiterLen - 1;
                                pos  = total - todo;
                            }
                        }

                        // 查询图片尾
                        while ((align == 2) && (todo >= boundaryLen))
                        {
                            stop = ByteArrayUtils.Find(buffer, boundary, pos, todo);
                            if (stop != -1)
                            {
                                pos  = stop;
                                todo = total - pos;

                                // 帧计数器增加
                                framesReceived++;

                                // 产生新帧事件
                                if (NewFrame != null)
                                {
                                    Bitmap bmp = (Bitmap)Bitmap.FromStream(new MemoryStream(buffer, start, stop - start));
                                    // 通知上层,新帧事件
                                    NewFrame(this, new CameraEventArgs(bmp));
                                    // 释放图片
                                    bmp.Dispose();
                                    bmp = null;
                                }

                                // 转移数组
                                pos  = stop + boundaryLen;
                                todo = total - pos;
                                Array.Copy(buffer, pos, buffer, 0, todo);

                                total = todo;
                                pos   = 0;
                                align = 1;
                            }
                            else
                            {
                                // delimiter没有找到
                                todo = boundaryLen - 1;
                                pos  = total - todo;
                            }
                        }
                    }
                }
                catch (WebException ex)
                {
                    System.Diagnostics.Debug.WriteLine("=============: " + ex.Message);
                    // 等待再一次尝试
                    Thread.Sleep(250);
                }
                catch (ApplicationException ex)
                {
                    System.Diagnostics.Debug.WriteLine("=============: " + ex.Message);
                    // 等待再一次尝试
                    Thread.Sleep(250);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("=============: " + ex.Message);
                }
                finally
                {
                    // 终止请求
                    if (req != null)
                    {
                        req.Abort();
                        req = null;
                    }
                    // 关闭响应流
                    if (stream != null)
                    {
                        stream.Close();
                        stream = null;
                    }
                    // 关闭响应
                    if (resp != null)
                    {
                        resp.Close();
                        resp = null;
                    }
                }

                if (stopEvent.WaitOne(0, true))
                {
                    break;
                }
            }
        }