Beispiel #1
0
        private void WebClientConnectionWorker(StreamClient client)
        {
            client.ClientPosition = _ringBuffer.NextAddPosition;
            var data = new byte[1500];

            while (true)
            {
                while (client.ClientPosition == _ringBuffer.NextAddPosition)
                {
                    Thread.Sleep(1);
                }

                if (client.ClientPosition > _ringBuffer.BufferSize)
                {
                    client.ClientPosition = 0;
                }

                int dataLen;
                if (_ringBuffer.Peek(client.ClientPosition, ref data, out dataLen) != 0)
                {
                    Console.WriteLine("Resizing buffer");
                    data = new byte[dataLen];
                    _ringBuffer.Peek(client.ClientPosition, ref data, out dataLen);
                }

                try
                {
                    if (dataLen != 0)
                    {
                        if (WebSocket != null)
                        {
                            if (WebSocket.State == WebSocketState.Open)
                            {
                                var arraySeg = WebSocket.CreateServerBuffer(data.Length);
                                Buffer.BlockCopy(data, RtpHeaderSize, arraySeg.Array, 0, data.Length - RtpHeaderSize);
                                WebSocket.SendAsync(arraySeg, WebSocketMessageType.Binary, true, new CancellationToken());
                            }
                            else
                            {
                                return;
                            }
                        }
                        else
                        {
                            client.OutputWriter.Write(data, RtpHeaderSize, dataLen - RtpHeaderSize);
                        }
                    }
                }
                catch (Exception)
                {
                    return;
                }
                client.ClientPosition++;
            }
        }
Beispiel #2
0
        public void TestPeek()
        {
            var ringBuffer = new RingBuffer(12); // 16 cap
            var buffer     = new byte[] { 1, 2, 3, 4, 5 };

            ringBuffer.Write(buffer);

            Assert.AreEqual(11, ringBuffer.WriteableCapacity);
            Assert.AreEqual(5, ringBuffer.ReadableCapacity);

            var data = ringBuffer.Peek();

            Assert.AreEqual(5, data.Length);
            Assert.AreEqual(1, data[0]);
            Assert.AreEqual(2, data[1]);
            Assert.AreEqual(3, data[2]);
            Assert.AreEqual(4, data[3]);
            Assert.AreEqual(5, data[4]);

            var data2 = new byte[5];
            var read  = ringBuffer.Peek(data2, 3);

            Assert.AreEqual(2, read);
            Assert.AreEqual(5, data2.Length);
            Assert.AreEqual(0, data2[0]);
            Assert.AreEqual(0, data2[1]);
            Assert.AreEqual(0, data2[2]);
            Assert.AreEqual(1, data2[3]);
            Assert.AreEqual(2, data2[4]);

            // double peek test
            data2 = new byte[5];
            read  = ringBuffer.Peek(data2);
            Assert.AreEqual(5, read);
            Assert.AreEqual(5, data2.Length);
            Assert.AreEqual(1, data2[0]);
            Assert.AreEqual(2, data2[1]);
            Assert.AreEqual(3, data2[2]);
            Assert.AreEqual(4, data2[3]);
            Assert.AreEqual(5, data2[4]);

            Assert.AreEqual(11, ringBuffer.WriteableCapacity);
            Assert.AreEqual(5, ringBuffer.ReadableCapacity);
            ringBuffer.Read();
            Assert.AreEqual(16, ringBuffer.WriteableCapacity);
            Assert.AreEqual(0, ringBuffer.ReadableCapacity);
        }
Beispiel #3
0
        public int Peek(TimeLocatedBuffer1D <T> target, int elements)
        {
            var timeBegin = TimeAtReadPosition;
            var read      = _buffer.Peek(target.Data, 0, elements);

            target.SetWritten(read, timeBegin.Increment(read, Samplerate));
            return(read);
        }
Beispiel #4
0
        public int Peek(TimeLocatedBufferFFT target, int frames)
        {
            var timeBegin = TimeAtReadPosition;
            var read      = _buffer.Peek(target.Data, 0, frames * FrameSize);

            if (read % FrameSize != 0)
            {
                throw new InvalidOperationException("shouldn't dequeue amount which is not a multiple of the frame size");
            }
            target.SetWritten(read / FrameSize, timeBegin.Increment(read * FrameSize, Samplerate));
            return(read / FrameSize);
        }
Beispiel #5
0
        public void TestReadEmptyBuffer()
        {
            var ringBuffer = new RingBuffer(4); // 4 cap
            var read       = ringBuffer.Read();

            Assert.AreEqual(0, read.Length);

            var peek = ringBuffer.Peek();

            Assert.AreEqual(0, peek.Length);

            var buffer = new byte[5];
            var r      = ringBuffer.Read(buffer, 2);

            Assert.AreEqual(0, r);
        }
Beispiel #6
0
        public void OverflowBufferTest(bool allowOverflow)
        {
            var bufferSize = 12;
            var dataCount  = 16;
            var dataSize   = 1;
            var didExcept  = false;

            Console.WriteLine($"Testing buffer addition for buffer size {bufferSize} with {dataCount} elements");
            try
            {
                var buffer = new RingBuffer(bufferSize, 1, allowOverflow);

                FillBufferWithFakeData(buffer, dataSize, dataCount);
                var checkValueBuffer = new byte[1];
                buffer.Peek(dataCount - bufferSize - 2, ref checkValueBuffer, out int dataPeekLength);

                if (checkValueBuffer[0] != dataCount - 1)
                {
                    Assert.Fail($"Unexpected value at circled buffer location - expected {dataCount -1}, found {checkValueBuffer[0]}");
                }

                for (int i = 4; i < dataCount; i++)
                {
                    buffer.Remove(ref checkValueBuffer, out int dataLength, out ulong timestamp);
                    if (checkValueBuffer[0] != i)
                    {
                        Assert.Fail($"Unexpected value at circled buffer location - expected {dataCount - 1}, found {checkValueBuffer[0]}");
                    }
                }
            }
            catch (Exception ex)
            {
                if (!(ex is OverflowException))
                {
                    Assert.Fail($"Failed LoopedBufferTest with buffer size {dataCount} - {ex.Message}");
                }

                didExcept = true;
            }

            if (allowOverflow && didExcept)
            {
                Assert.Fail($"Failed LoopedBufferTest with buffer size {dataCount} - overflow should be permitted, but OverflowException was thrown.");
            }
        }
Beispiel #7
0
        protected virtual void AppendData()
        {
            Display.Print(spinner[spinnerIndex]);
            spinnerIndex = (spinnerIndex + 1) % spinner.Length;
            Display.MoveLeft();

            byte b = dataBuffer.Peek();

            if (dataBuffer.Count >= BLOCK_LENGTH)
            {
                // SOH begins an XMODEM block
                // read until we get a valid SOH and then
                // enter the block.
                if (b == SOH)
                {
                    Stage = TransferStages.Data;
                    ProcessBuffer();
                }
                else
                {
                    dataBuffer.Read();
                }
            }
            if (b == ETX) // cancel
            {
                dataBuffer.Read();
                Display.PrintSeparater();
                Display.PrintAtStart("Canceled by remote host.");
                Cancel();
            }
            else if (b == EOT)
            {
                dataBuffer.Read();
                SendACK();
                CompleteReceive();
            }
        }
Beispiel #8
0
        void _ProcessReceivedData(ref DaemonParameter daemonParameter)
        {
            RingBuffer <byte> dataBuffer = daemonParameter.daemonObject.receiveCache;

            while (!dataBuffer.IsEmpty)
            {
                // 拆包,按完整消息返回给Handler
                // 寻找魔数
                if (dataBuffer.DiscardToFirstIndexOf(0xC8, 0xEF))
                {
                    byte headLength = 0;
                    if (dataBuffer.Length >= 3)
                    {
                        // 找到了魔数,而且数据长度足够解析出消息头长度
                        // 解析出消息头长度
                        dataBuffer.Peek(2, out headLength);
                    }
                    else
                    {
                        // 消息接收长度还不够,继续接收
                        if (LogUtil.ShowDebug != null)
                        {
                            LogUtil.ShowDebug("消息头没收全,继续接收1");
                        }
                        break;
                    }
                    // 进一步解析出整个消息头
                    if (headLength > 0 && dataBuffer.Length >= headLength)
                    {
                        if (headLength < ProtocolDefine.minimalHeadLength)
                        {
                            // 万一消息头长度不满足协议定义的最小长度,说明收到了一条非本系统能够处理的协议,抛弃(直接抛弃协议头即可,协议体会自然在下一个循环里被抛弃掉)
                            dataBuffer.Discard(headLength);
                            if (LogUtil.ShowDebug != null)
                            {
                                LogUtil.ShowDebug("收到的消息头不满足系统定义的最小消息头长度,抛弃");
                            }
                            continue;
                        }
                        // 解析出了消息头长度,而且数据长度足够解析出整个消息头
                        // 解析出消息头里的必要数据
                        byte token;
                        dataBuffer.Peek(5, out token);
                        // 获得心跳标识位
                        bool heartBeat = (token & ProtocolDefine.heartBeatMask) != 0;

                        /*
                         * // 获得单向消息标识位
                         * bool oneWay = (token & ProtocolDefine.oneWayMask) != 0;
                         * // 获得响应消息标识位
                         * bool response = (token & ProtocolDefine.responseMask) != 0;
                         * // 获得加密标识位
                         * bool encrypt = (token & ProtocolDefine.encryptMask) != 0;
                         * // 获得加密方式
                         * int encryptType = (token & ProtocolDefine.encryptTypeMask) >> ProtocolDefine.encryptTypeBitRightOffset;
                         * // 获得压缩标识位
                         * bool compress = (token & ProtocolDefine.compressMask) != 0;
                         * // 获得拆分标识位
                         * bool split = (token & ProtocolDefine.splitMask) != 0;
                         */
                        // 如果是心跳消息,那么记录下收到的时间,抛弃消息头(心跳消息没有消息体,所以抛弃消息头就抛弃了整条心跳消息)
                        if (heartBeat)
                        {
                            daemonParameter.lastHeartBeatReturnTime = DateTimeUtil.NowMillisecond;
                            dataBuffer.Discard(headLength);
                            continue;
                        }
                        // @TODO: 处理拆分的包,要将不完整的包临时放入一个为超大包准备的缓存,直到所有拆开的包体都收到了再合并成完整的包
                        byte[] bodyLengthBytes = new byte[2];
                        dataBuffer.Peek(10, out bodyLengthBytes[0]);
                        dataBuffer.Peek(11, out bodyLengthBytes[1]);
                        short bodyLength = BitConverterEx.GetShort(bodyLengthBytes, 0, true);
                        if (dataBuffer.Length >= (headLength + bodyLength))
                        {
                            // 数据长度满足协议头和协议体,即完整消息已经接收到了
                            byte[] msgBytes = new byte[headLength + bodyLength];
                            if (dataBuffer.TryPull(msgBytes.Length, ref msgBytes) && daemonParameter.daemonObject.DataHandler != null)
                            {
                                daemonParameter.daemonObject.DataHandler.OnDataReceived(daemonParameter.daemonObject, msgBytes);
                            }
                        }
                        else
                        {
                            // 消息接收长度还不够,继续接收
                            if (LogUtil.ShowDebug != null)
                            {
                                LogUtil.ShowDebug("消息体没收全,继续接收");
                            }
                            break;
                        }
                    }
                    else
                    {
                        // 消息接收长度还不够,继续接收
                        if (LogUtil.ShowDebug != null)
                        {
                            LogUtil.ShowDebug("消息头没收全,继续接收2");
                        }
                        break;
                    }
                }
                else
                {
                    dataBuffer.DiscardAll();
                }
            }
        }
Beispiel #9
0
        public void ThreadedLoopedPeekTest()
        {
            //this test creates a thread to reliably add a buffer sample with a new element added every 5 milliseconds.
            //it then consumes the buffer, taking a randomized time between 1 and 8 ms to eat a sample - it should trigger the
            //buffer to fill and empty with some realistic behaviour

            var bufferSize = 48;
            var dataSize   = 1;
            var cycleCount = 409;

            var data   = new byte[dataSize];
            var buffer = new RingBuffer(bufferSize, 1, true);

            var ts = new ThreadStart(delegate
            {
                AddingThread(buffer, cycleCount);
            });

            var addingThread = new Thread(ts)
            {
                Priority = ThreadPriority.Highest
            };

            addingThread.Start();

            var  readPosition   = 0;
            var  iterationCount = 0;
            byte expectedVal    = 0;

            var randomGenerator = new Random();
            var stringResult    = new StringBuilder(1024);
            var sleepCount      = 0;

            while (addingThread.IsAlive)
            {
                var randSleep = randomGenerator.Next(1, 8);

                if (readPosition > buffer.BufferSize)
                {
                    readPosition = 0;
                }

                if (readPosition == buffer.NextAddPosition)
                {
                    Thread.Sleep(randSleep);
                    sleepCount++;
                    continue;
                }

                data[0] = 0;
                try
                {
                    buffer.Peek(readPosition, ref data, out int dataLength);
                }
                catch (Exception ex)
                {
                    Assert.Fail($"Failed ThreadedLoopedBufferTest on read iteration {iterationCount} - exception: {ex.Message}.");
                }
                var result = data[0];

                if (result != expectedVal)
                {
                    Assert.Fail($"Failed ThreadedLoopedBufferTest on read iteration {iterationCount} - expected value {expectedVal}, got {result}.");
                }

                stringResult.Append($"{result},");

                expectedVal = ++result;
                readPosition++;
                iterationCount++;
            }

            Console.WriteLine($"Sleep count: {sleepCount}");
            Console.WriteLine(stringResult.ToString());
        }
 public void PeekTest_1()
 {
     RingBuffer<int> rb = new RingBuffer<int>(4);
     rb.Add(3);
     rb.Add(5);
     int p1 = rb.Peek();
     int d1 = rb.Remove();
     int p2 = rb.Peek();
     int d2 = rb.Remove();
     Assert.AreEqual(3, p1);
     Assert.AreEqual(5, p2);
     Assert.AreEqual(3, d1);
     Assert.AreEqual(5, d2);
 }
 public void PeekTest_0()
 {
     RingBuffer<int> rb = new RingBuffer<int>(4);
     int d = rb.Peek();
 }