Exemple #1
0
        public void ByteStreamShouldReturnCharA()
#endif
        {
            ISocket socket = A.Fake <ISocket>();

            using (INetworkStream networkStream = A.Fake <INetworkStream>())
            {
                A.CallTo(() => socket.GetStream()).Returns(networkStream);
                A.CallTo(() => socket.Connected).Returns(true);
                bool isFirst = true;
                A.CallTo(() => socket.Available).ReturnsLazily(() =>
                {
                    if (isFirst)
                    {
                        isFirst = false;
                        return(1);
                    }
                    return(0);
                });
                TcpByteStream tcpByteStream = new TcpByteStream(socket);
                A.CallTo(() => networkStream.ReadByte()).ReturnsNextFromSequence(65);
                tcpByteStream.Connected.Should().BeTrue();
                ByteStreamHandler sut = new ByteStreamHandler(tcpByteStream, new CancellationTokenSource());

#if ASYNC
                string response = await sut.ReadAsync(TimeSpan.FromMilliseconds(10));
#else
                string response = sut.Read(TimeSpan.FromMilliseconds(10));
#endif

                response.Should().Be("A");
            }
        }
        public void WhenIacDoSgaByteStreamShouldReturnEmptyAndReplyIacWill()
#endif
        {
            ISocket socket = A.Fake <ISocket>();

            using (INetworkStream networkStream = A.Fake <INetworkStream>())
            {
                A.CallTo(() => socket.GetStream()).Returns(networkStream);
                A.CallTo(() => socket.Connected).Returns(true);
                bool isFirst = true;
                A.CallTo(() => socket.Available).ReturnsLazily(() =>
                {
                    if (isFirst)
                    {
                        isFirst = false;
                        return(1);
                    }
                    return(0);
                });
                TcpByteStream tcpByteStream = new TcpByteStream(socket);
                A.CallTo(() => networkStream.ReadByte()).ReturnsNextFromSequence(new int[] { (int)Commands.InterpretAsCommand, (int)Commands.Do, (int)Options.SuppressGoAhead });
                tcpByteStream.Connected.Should().BeTrue();
                ByteStreamHandler sut = new ByteStreamHandler(tcpByteStream, new CancellationTokenSource());

#if ASYNC
                string response = await sut.ReadAsync(TimeSpan.FromMilliseconds(10));
#else
                string response = sut.Read(TimeSpan.FromMilliseconds(10));
#endif
                response.Should().BeEmpty();
                A.CallTo(() => networkStream.WriteByte((byte)Commands.InterpretAsCommand)).MustHaveHappened();
                A.CallTo(() => networkStream.WriteByte((byte)Commands.Will)).MustHaveHappened();
            }
        }
Exemple #3
0
        public void ByteStreamShouldReturnUponCancellation()
#endif
        {
            ISocket        socket        = A.Fake <ISocket>();
            INetworkStream networkStream = A.Fake <INetworkStream>();

            A.CallTo(() => socket.GetStream()).Returns(networkStream);
            A.CallTo(() => socket.Connected).Returns(true);
            A.CallTo(() => socket.Available).Returns(1);
            TcpByteStream tcpByteStream = new TcpByteStream(socket);

            A.CallTo(() => networkStream.ReadByte()).Returns(142);
            tcpByteStream.Connected.Should().BeTrue();
            CancellationTokenSource cancellationToken = new CancellationTokenSource();

            Stopwatch         stopwatch = new Stopwatch();
            ByteStreamHandler sut       = new ByteStreamHandler(tcpByteStream, cancellationToken);

#if ASYNC
            cancellationToken.CancelAfter(100);
            await sut.ReadAsync(TimeSpan.FromMilliseconds(1000));
#else
            Thread t = new Thread(new ThreadStart(() =>
            {
                AutoResetEvent are = new AutoResetEvent(false);
                are.WaitOne(100);
                cancellationToken.Cancel();
            }));
            t.Start();
            sut.Read(TimeSpan.FromMilliseconds(1000));
#endif

            stopwatch.ElapsedMilliseconds.Should().BeLessThan(500);
        }
Exemple #4
0
        public void GivenAFakedSocketACallToReadByteShouldBeRelayed()
        {
            ISocket        socket = A.Fake <ISocket>();
            INetworkStream stream = A.Fake <INetworkStream>();

            A.CallTo(() => socket.GetStream()).Returns(stream);
            TcpByteStream sut = new TcpByteStream(socket);

            sut.ReadByte();

            A.CallTo(() => stream.ReadByte()).MustHaveHappened();
        }
		protected override void ConstructFromStream(INetworkStream str)
        {
            // Read the message ID that the server is acknowlodging
            _ackID = ReadUshortFromStream(str);
            int qosCount = variableHeaderLength - 2;
            grantedQos = new QoS[qosCount];

            for (int i = 0; i < qosCount; i++)
            {
                int res = str.ReadByte();
                if (res != -1)
                {
                    grantedQos[i] = (QoS)res;
                }
                else
                {
                    throw new Exception("Failed to read byte from stream");
                }
            }


        }
        //------------------------------------------------------------------------------
        //
        // Method: WaitForMessageAcknowledgement
        //
        //------------------------------------------------------------------------------
        /// <summary>
        /// Checks for a message acknowledgement on the specified network stream, and throws an exception if the acknowledgement is not received before the specified timeout period.
        /// </summary>
        /// <param name="networkStream">The network stream to attempt to read the acknowledgement from.</param>
        private void WaitForMessageAcknowledgement(INetworkStream networkStream)
        {
            bool      acknowledgementReceived = false;
            Stopwatch acknowledgementTimer    = new Stopwatch();

            acknowledgementTimer.Start();
            while ((acknowledgementTimer.ElapsedMilliseconds <= acknowledgementReceiveTimeout) && (acknowledgementReceived == false))
            {
                int availableData = client.Available;
                if (availableData > 0)
                {
                    if (availableData > 1)
                    {
                        throw new Exception("Surplus data encountered when receiving acknowledgement.  Expected 1 byte, but received " + availableData.ToString() + ".");
                    }

                    int acknowledgementByte = networkStream.ReadByte();
                    if (acknowledgementByte != (int)messageAcknowledgementByte)
                    {
                        throw new Exception("Acknowledgement byte was expected to be " + messageAcknowledgementByte.ToString() + ", but was " + acknowledgementByte.ToString() + ".");
                    }
                    else
                    {
                        acknowledgementReceived = true;
                    }
                }

                if (acknowledgementReceiveRetryInterval > 0)
                {
                    Thread.Sleep(acknowledgementReceiveRetryInterval);
                }
            }

            if (acknowledgementReceived == false)
            {
                throw new MessageAcknowledgementTimeoutException("Failed to receive message acknowledgement within timeout period of " + acknowledgementReceiveTimeout.ToString() + " milliseconds.");
            }
        }
Exemple #7
0
        /// <summary>
        /// Decodes the length of the variable header and payload from the given stream
        /// </summary>
        /// <param name="str">Input Stream</param>
        /// <returns>Length of the variable header and the payload</returns>
        private int DecodeVariableHeaderLength(INetworkStream str)
        {
            int multiplier = 1 ;
            int value = 0 ;
            int digit = 0;

            do
            {
                digit = str.ReadByte();
                if (digit == -1)
                {
                    return 0;
                }
                value += (digit & 127) * multiplier;
                multiplier *= 128;
            }
            while ((digit & 128) != 0);

            return value;
        }